我正在尝试在 SwiftUI 中开始点击按钮时实现触觉反馈。因此,我正在尝试使用 simultaneousGesture,但我仍在苦苦挣扎。我无法弄清楚水龙头何时开始。
Swift UI 也没有实现触觉反馈,所以我想我会从 UIKit 中融入它?
我试图实现 TapGesture 的更新方法,但它似乎没有做任何事情。这是我到目前为止所得到的。感谢您的任何提示。
struct HapticButton : View {
@GestureState var isDetectingTap = false
var body: some View {
let tap = TapGesture()
.updating($isDetectingTap) { (body, stateType, transaction) in
// nothing happens below
print(body)
print(stateType)
print(transaction)
}.onEnded { _ in
// this one works but it is to late
// I need to figure out the beginning of the tap
print("Button was tapped, will invoke haptic feedback, maybe with UIKit")
}
return Button(action: {
print("Action executed")
}) {
HStack {
Image("icon")
Text("Login")
}
}.simultaneousGesture(tap)
}
}
最佳答案
据我所知,这是在 SwiftUI 中获得触觉反馈的最简单方法
点击按钮时:
Button(action: {
let impactMed = UIImpactFeedbackGenerator(style: .medium)
impactMed.impactOccurred()
}) {
Text("This is a Button")
}
您可以通过将 .medium
替换为 .soft
、.light
、.heavy< 来更改触觉反馈的强度
,或 .rigid
或点击其他任何东西时:
.onTapGesture {
let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
impactHeavy.impactOccurred()
}
如果你想制作类似 Haptic Touch 的东西,请将 .onTapGesture
替换为 .onLongPressGesture
,如下所示
.onLongPressGesture {
let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
impactHeavy.impactOccurred()
}
关于ios - 如何在 SwiftUI 中为按钮创建触觉反馈?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56748539/