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

问题描述 投票:0回答:5

在 SwiftUI 中更改按钮背景颜色的最佳方法是什么?

我想创建一个图块,它是一个带有居中文本和某种颜色的矩形背景的按钮。

button swiftui
5个回答
41
投票

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

32
投票

您可以直接向按钮添加修改,无需任何容器(例如:组)

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

希望能帮助别人!


32
投票

如果您使用 .buttonStyle(style:) 修饰符并想要更改背景颜色,请使用 .tint(tint:) 而不是 .background(alignment:content)。例如,您可以通过以下方式将 .borderedProminent 按钮样式更改为绿色:

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


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

这就是整个背景可点击的方式


0
投票

SwiftUI 颜色

从 iOS v13 及更高版本开始,当您使用颜色时,应考虑浅色和深色模式。

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

例如,深色模式下的 .black 将不可见(黑底黑字)。您可以使用系统颜色作为变体。例如

UIColor.label

© www.soinside.com 2019 - 2024. All rights reserved.