MacOS 上 SwiftUI 中的按钮问题 [英] Issue with Buttons in SwiftUI on MacOS

查看:35
本文介绍了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()
    }
}

这篇关于MacOS 上 SwiftUI 中的按钮问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆