单击按钮 (x) 次后振动

Vibrate after a button is clicked (x) amount of times

正如标题所说,我试图在单击按钮 x 次时触发振动。 例如,当按钮被点击 3 次时,我想要振动。

这是我正在使用的代码:

import SwiftUI
import AudioToolbox


struct ContentView: View {
    var body: some View {
        VStack{
            
            Button("Press"){
                AudioServicesPlayAlertSoundWithCompletion(SystemSoundID(kSystemSoundID_Vibrate)) {   }
               
            }
            
        }
        
    }
}

您需要增加一个值,然后在达到该值后执行某些操作。这很简单,一个简单的方法可以像下面这样完成。

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
    }
}