如何在SwiftUI中为按钮创建触觉反馈? [英] How to create haptic feedback for a Button in SwiftUI?
问题描述
我正在尝试在SwiftUI中为Button轻按开始时实现触觉反馈.因此,我正在尝试同时使用手势,但是我仍在挣扎.我无法弄清楚水龙头何时开始.
I'm trying to implement haptic feedback at the beginning of a tap for a Button in SwiftUI. Therefore I'm trying to use simultaneousGesture, but I'm sill struggling. I can't manage to figure out when the tap begins.
还没有为Swift UI实施触觉反馈,所以我想我可以从UIKit中将其融合进来?
Also there is no Haptic feedback implemented for Swift UI, so I guess I would blend it in from UIKit?
我试图实现TapGesture的更新方法,但它似乎无能为力.到目前为止,这就是我所得到的.谢谢你的提示.
I tried to implement the updating method of the TapGesture but it does not seem to do anything. This is what I've got so far. Thanks for any hints.
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中获取触觉反馈的最简单方法
As I know, this is the most simplest way to get haptic feedback in SwiftUI
点击按钮时:
Button(action: {
let impactMed = UIImpactFeedbackGenerator(style: .medium)
impactMed.impactOccurred()
}) {
Text("This is a Button")
}
您可以通过将 .medium
替换为 .soft
, .light
, .heavy
或 .rigid
You can change the intensity of the haptic feedback by replacing .medium
with .soft
, .light
, .heavy
, or .rigid
或在点击其他任何内容时:
.onTapGesture {
let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
impactHeavy.impactOccurred()
}
如果您想制作类似Haptic Touch的内容,请像这样用 .onLongPressGesture
替换 .onTapGesture
If you want to make something like Haptic Touch, replace .onTapGesture
with .onLongPressGesture
like this
.onLongPressGesture {
let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
impactHeavy.impactOccurred()
}
这篇关于如何在SwiftUI中为按钮创建触觉反馈?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!