如何在 SwiftUI 中同时实现声音和振动

问题描述

注释 onTapGesture 会激活声音。但振动不起作用。如何同时实现声音和振动?

为什么会出现这个问题?

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

解决方法

在您的 Button 操作中,同时调用 activeNum()impactOccured(),而不是尝试将后者放在单独的 onTapGesture 中:

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