效果演示
关键部分代码
struct PowerButtonView: View {
@Binding var dragAmount: CGFloat
@Binding var powerOn: Bool
@Binding var showSlideText: Bool
@Binding var showCheckmarkProgress: Double
var body: some View {
HStack {
Image(systemName: powerOn ? "circle.fill" : "power.circle.fill")
.font(.system(size: 52))
// 根据滑动量调整图片位置
.offset(x: self.dragAmount)
// 添加手势识别
.gesture(powerGesture())
if showSlideText && dragAmount <= 10 {
Text("向右滑动解锁")
.foregroundColor(.black)
.frame(width: 150)
.shimmering()
}
Spacer()
CheckMarkView(showCheckmarkProgress : $showCheckmarkProgress,
dragAmount : $dragAmount)
}
}
private func powerGesture() -> some Gesture {
DragGesture()
.onChanged { value in
if value.translation.width > 0 && value.translation.width < 190 {
self.dragAmount = value.translation.width
}
}
.onEnded { value in
// 当滑动结束时,根据滑块位置决定是否激活
if dragAmount >= 180 {
self.dragAmount = 188
powerOn = true
withAnimation(Animation.easeInOut(duration: 1)) {
// 开启动画
showCheckmarkProgress = 1
}
} else {
// 如果未滑动到指定位置,则复位
withAnimation(.interpolatingSpring(stiffness: 200, damping: 10)) {
self.dragAmount = 0
self.showSlideText = false
}
}
// 延迟0.2秒后再次显示滑动提示文本
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2){
withAnimation {
self.showSlideText = true
}
}
}
}
}