Home > Software design >  Vibrate after a button is clicked (x) amount of times
Vibrate after a button is clicked (x) amount of times

Time:05-07

As the title says i am trying to trigger a vibration when the button is clicked x amount of times. For example when the button is clicked 3 times I want a vibration.

This is the code i am using:

import SwiftUI
import AudioToolbox


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

CodePudding user response:

You'd need increment a value, then once the value is reached do something. It's fairly straightforward, a simple approach could be done like this below.

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

increment

  • Related