在浅色和深色模式之间切换时,按钮文本无法正确更改颜色。在浅色模式下,它显示为带有白色文本的黑色按钮。在黑暗模式下,它只显示一个白色按钮,其中可能有白色文本。我正在寻求应用一种在亮/暗模式下自动适应的样式。
struct Primary: View {
var body: some View {
Button("hello") {}
.buttonStyle(.borderedProminent)
.tint(.primary)
// .disabled(true) // optional
}
}
我尝试拆分按钮初始化,以便我可以直接修改文本,但没有成功。添加 .disabled 修饰符时它会正确显示。
您可以使用
.foregroundColor()
初始值设定项中的 Button
修饰符直接设置文本颜色。使用 .primary
作为颜色可确保它根据外观模式自动调整。这是一个例子:
struct Primary: View {
var body: some View {
Button(action: {}) {
Text("hello")
.foregroundColor(.primary) // Adjusts text color for light/dark mode
}
.buttonStyle(.borderedProminent)
.tint(.primary) // Adjusts button's background and border color
}
}