0

所以我通过本教程了解了如何让手机提供触觉反馈。 https://swifttom.com/2020/03/11/haptic-feedback-in-a-swiftui-button/

但是,我想弄清楚的是如何让 iPhone 真正振动,就像在电话静音时接听电话或计时器(来自默认时钟应用程序)关闭时发生的振动一样。我知道这似乎我可以在 Google 上轻松找到答案,但老实说我找不到解决方案。如果有人可以提供帮助,将不胜感激。

import SwiftUI

struct ContentView: View {
    let generator = UINotificationFeedbackGenerator()
    var body: some View {
        VStack{
            Button("Press") {
                generator.notificationOccurred(.error) //I want vibration, not haptic feedback
            }
        }
    }
}
4

3 回答 3

2

我认为这应该会有所帮助。试试看!Lmk 如果它有效!

源代码

import SwiftUI
import AudioToolbox


struct ContentView: View {
    var body: some View {
        VStack{
            
            Button("Press"){
                AudioServicesPlayAlertSoundWithCompletion(SystemSoundID(kSystemSoundID_Vibrate)) {   }
               
            }
            
        }
        
    }
}
于 2021-09-08T06:50:28.530 回答
1

只要打电话AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)。您可能需要导入 AudioToolbox 框架。

于 2021-09-08T01:42:53.917 回答
0

1.首先需要导入AudioToolbox

当我点击按钮时,我正在使用振动功能。

@IBAction func startVibration(_ sender: Any) { for _ in 1...5 { AudioServicesPlaySystemSound(kSystemSoundID_Vibrate) sleep(1) } }

它的工作正常。

2.让它成为 UIDevice 的扩展?

扩展 UIDevice { static func vibrate() { AudioServicesPlaySystemSound(kSystemSoundID_Vibrate) } }

现在您可以根据需要调用 UIDevice.vibrate() 。

于 2021-09-08T07:01:03.617 回答