站点图标 Codeun

SwiftUI 自定义单选多选按钮 Checkmark 选中动画

SwiftUI 单选多选按钮动画效果

通常做一个单选多选按钮会使用 Toggle 来制作,我这里提供一种自定义实现 CheckMark 的方式如下。

效果演示

https://www.codeun.com/wp-content/uploads/2024/11/2024111907560462.mp4
SwiftUI 多选单选按钮选中动画效果

示例代码

 
import SwiftUI

struct CheckMarkAnimation: View {
    @State var isTapped = false
    @State var Animated = false
    @State var scale:CGFloat = 1
    var body: some View {
        
        ZStack {
            ForEach(0..<6) { i in
                Circle().frame(width: 30, height:30)
                    .scaleEffect(Animated ? 0 : 1)
                    .offset(y:Animated ? -50 : 0)
                    .rotationEffect(.degrees(Double(i) * 60))
                    .opacity(Animated ? 1 : 0)
            }
            
            Image(systemName:isTapped ? "checkmark.circle" : "circle")
                .contentTransition(.symbolEffect).font(.largeTitle)
        }
        .foregroundStyle(isTapped ? .indigo : .white)
        .onTapGesture {
            withAnimation(.spring(duration: 1)) {
                isTapped.toggle()
            }
            withAnimation(isTapped ?.spring(duration: 1) : .none) {
                Animated.toggle()
            }
        }  
    }
}

#Preview {
    CheckMarkAnimation()
}

示例代码下载


退出移动版