ios - 如何在 SwiftUI 中为按钮创建触觉反馈?

标签 ios

我正在尝试在 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/

相关文章:

ios - 如何检测核心数据对象关系属性变化

ios - 如何在 iphone 中点击应用程序图标时清除角标(Badge)计数器?

ios - iOS 中使用实时摄像头的 Firebase MLKit 文本识别

ios - 如何获取 AVCaptureDevice 的当前温度和色调?

iphone - 如何排序包含NSDictionaries的NSArray?

ios - 如何在 iOS info.plist 文件中本地化字符串数组

ios - 世博会 React Native 应用程序。使用 expo-secure-store 方法时出错 [该方法或属性 SecureStore.setItemAsync 在 ios 上不可用]

ios - FW 和 TW 的自定义登录

ios - 如何在 iOS 包中包含文件夹层次结构中的所有文件,但不包含文件夹本身?

iphone - 在iOS 5中发布UIviewController对象?