正如標題所說,我試圖在單擊按鈕 x 次時觸發振動。例如,當按鈕被單擊 3 次時,我想要振動。
這是我正在使用的代碼:
import SwiftUI
import AudioToolbox
struct ContentView: View {
var body: some View {
VStack{
Button("Press"){
AudioServicesPlayAlertSoundWithCompletion(SystemSoundID(kSystemSoundID_Vibrate)) { }
}
}
}
}
uj5u.com熱心網友回復:
您需要增加一個值,然后在達到該值后執行某些操作。這相當簡單,一個簡單的方法可以像下面這樣完成。
import SwiftUI
import AudioToolbox
struct ContentView: View {
@State var value = 0
var body: some View {
HStack {
Button(action: increment) {
Label("\(value)", systemImage: "number")
.labelStyle(.titleOnly)
.frame(minWidth: 0, maxWidth: .infinity)
}
.buttonStyle(.borderedProminent)
Button(action: reset) {
Label("Reset", systemImage: "arrow.triangle.2.circlepath")
.frame(minWidth: 0, maxWidth: .infinity)
}
.buttonStyle(.borderedProminent)
}
.padding()
.onChange(of: value, perform: { value in
// if value = 3 play alert sound
if value == 3 {
AudioServicesPlayAlertSoundWithCompletion(SystemSoundID(kSystemSoundID_Vibrate), nil)
}
})
}
private func increment() {
// increment value here
value = 1
}
private func reset() {
// reset value
value = 0
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/470120.html