如何解决无法在 SwiftUI 中为 TapGesture 应用“.onChanged”方法
如果尝试运行以下代码,我会收到以下错误:
// Type 'TapGesture.Value' (aka '()') cannot conform to 'Equatable'
这是一个代码:
struct PressButton: View {
@Binding var pressed: Bool
var body: some View {
ZStack {
Circle()
.gesture(
TapGesture()
.onChanged { _ in pressed = true } // ERROR
.onEnded { _ in pressed = false }
)
}
}
}
但是,.onEnded { _ in }
方法运行良好。
解决方法
正如 onChanged
的 documentation 所述,当 Gesture
为 Gesture.Value
时,该方法仅在 Equatable
上可用。但是,TapGesture.Value
是 Void
,而不是 Equatable
,因此 TapGesture
没有 onChanged
方法。
但是,onEnded
可用于所有 Gesture
符合类型。
TapGesture
没有状态,只有在发生点击后被调用。
您要查找的是 LongPressGesture
,它确实将状态公开为 Bool
。
没有
.onChanged { _ in pressed = true }
带有 TapGesture
的修饰符,请检查其他有它的修饰符
https://www.hackingwithswift.com/books/ios-swiftui/how-to-use-gestures-in-swiftui
,我通过 DragGesture(minimumDistance: 0.0)
找到了一个可行的解决方案:
struct DrawButton: View {
@Binding var pressed: Bool
var body: some View {
ZStack {
Circle()
.foregroundColor(pressed ? .red : .black)
.gesture(DragGesture(minimumDistance: 0.0)
.onChanged { _ in pressed = true }
.onEnded { _ in pressed = false }
)
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。