0

I have a ButtonStyle for macOS app which change different background color depend on different behaviors.

  • White background when nothing happens.
  • Gray background when I hover on it.
  • Red background when I press on it.

I managed to finish the first two. But don't know how to achieve the third one, because there's no such method called onPress {}. I tried onTapGesture {}, but it only update background after I released the mouse, while I want it change background immediately when I press on it.

struct PlayerButton: ButtonStyle {
    
    @State private var background: Color
    
    init() {
        self.background = .white
    }
    
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .frame(width: 32, height: 28, alignment: .center)
            .background(background)
            .onHover { onHover in
                self.background = onHover ? .gray : .white
            }
            // Here doesn't work as I'm expected
            .onTapGesture {
                self.background = .red
            }
    }
    
}

And I also have a shortcut for this button. I want it performs when I use shortcut the same as when I press on it.

struct ContentView: View {
    var body: some View {
        Button {
            print("Hello World!")
        } label: {
            Image(systemName: "heart")
        }
        .keyboardShortcut(.space, modifiers: [])   // There's the shortcut
        .buttonStyle(PlayerButton())
    }
}
Yiming Designer
  • 423
  • 3
  • 10

0 Answers0