MacOS上SwiftUI中的按钮问题

问题描述:

我正在MACOS上使用SwiftUI

如果我这样做:

      Button(action: { } ) {
        Text("Press")
        .padding()
        .background(Color.blue)
      }

我明白了:

和两个灰色区域是可轻击按钮的末端. 但我希望按钮是蓝色区域的形状. 关于如何使整个蓝色区域都可轻敲的任何想法.

and the two grey areas are the ends of a tappable button. but I would expect the button to be the shape of the blue area. Any ideas how I can get the whole blue area to be tappable.

(我确实看过使用.onTapGesture的方法,但这并没有为按钮设置动画,以便您知道已轻按它.)

(I did look at using .onTapGesture but this doesn't animate the button so that you know you've tapped it.)

您可以使用 ButtonStyle ,然后根据传入的配置值指定颜色和其他样式属性.

You can achieve the look you want by using a ButtonStyle and then specifying colors and other style attributes based on the configuration values being passed in.

如果有一个令人满意的媒介,您可以继承默认的按钮半径,基于文本长度和其他属性的自动宽度,那将是很好的选择,但是至少可以指定所有属性并获得外观想要.

It would be nice if there was a happy medium where you could inherit the default button radius, automatic width based on the text length and other attributes, but at least there is the ability to specify all the attributes and get the look you want.

希望这会有所帮助!

import SwiftUI

struct BlueButtonStyle: ButtonStyle {
    func makeBody(configuration: Self.Configuration) -> some View {
        configuration.label
            .foregroundColor(configuration.isPressed ? Color.blue : Color.white)
            .background(configuration.isPressed ? Color.white : Color.blue)
            .cornerRadius(6.0)
            .padding()
    }
}

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Hello World")
                .frame(maxWidth: .infinity, maxHeight: .infinity)

            Button(action: {
            }) {
                Text("Press")
                    .frame(maxWidth: 100, maxHeight: 24)
            }
            .buttonStyle(BlueButtonStyle())
        }
    }
}


struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}