简体   繁体   English

如何更改 SwiftUI 中按钮的背景颜色?

[英]How can I change background color of button in SwiftUI?

What is the best way to change the button's background color in SwiftUI?在 SwiftUI 中更改按钮背景颜色的最佳方法是什么?

I want to create a tile which is a button with centered Text and rectangular background of some color.我想创建一个图块,它是一个带有居中文本和某种颜色的矩形背景的按钮。

在此处输入图像描述

Button(action: { }) {
    Text("Button Text!").padding()
}
.background(Color.black)

在此处输入图像描述

You can add a modified directly to the button without any containers (ex: Group)您可以直接将修改添加到按钮,无需任何容器(例如:组)

Button(action: {}) {
    Text("Click me!")
}
.padding()
.foregroundColor(.white)
.background(Color.red)

Hoping to help someone!希望能帮助到某人!

            Button(action: {self.buttonTapped()}) {
            Text("Button")
                .padding(.all, 12)
                .foregroundColor(.white)
                .background(Color.red)
        }

that's how the whole bg is clickable这就是整个bg是可点击的

SwiftUI color SwiftUI 颜色

From iOS v13 and above, when you work with colors you should take into account Light and Dark mode.从 iOS v13 及更高版本开始,当您使用颜色时,您应该考虑 Light 和 Dark 模式。

.foregroundColor(.red)
.background(.blue)

For example .black in dark mode will be invisible(black on black).例如,黑暗模式下的 .black 将是不可见的(黑底黑字)。 You can use system colors as a variant.您可以使用系统颜色作为变体。 For example UIColor.label例如UIColor.label

Also in SwiftUI, if you're using the .buttonStyle and want to change the background color, you'd use .tint, not .background.同样在 SwiftUI 中,如果您使用 .buttonStyle 并想要更改背景颜色,您将使用 .tint,而不是 .background。 For example, this is how you can change a borderedProminent button style to green:例如,您可以通过以下方式将borderedProminent 按钮样式更改为绿色:

Button("Press Me!") {
    //stuff to do
}
.buttonStyle(.borderedProminent)
.tint(.green)

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM