swiftuihaptic-feedback

How to implement sound and vibration together in SwiftUI


Annotating onTapGesture activates sound. But the vibration doesn't work. How to implement sound and vibration together?

Why does this problem occur?

let feedback = UIImpactFeedbackGenerator(style: .soft)

func activeNum() {
    playSound(sound: "casino-chips", type: "mp3")
}

var body: some View {
    ZStack {
        VStack(spacing: 0) {
            LogoView()
            
            Spacer()
            
            Button(action: {
                self.activeNum()
            }) {
                Image(systemName: "heart.fill")
                    .resizable()
                    .frame(width: 100, height: 100, alignment: .center)
                    .foregroundColor(.gray)
//                        .onTapGesture {
//                            feedback.impactOccurred()
//                        }
            }
            
            Spacer()
        }
    }
}

Solution

  • In your Button action, call both activeNum() and impactOccured() rather than trying to put the latter in a separate onTapGesture:

    Button(action: {
     self.activeNum()
     feedback.impactOccurred()
    }