簡體   English   中英

如何更改 SwiftUI 中按鈕的背景顏色?

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

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

我想創建一個圖塊,它是一個帶有居中文本和某種顏色的矩形背景的按鈕。

在此處輸入圖像描述

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

在此處輸入圖像描述

您可以直接將修改添加到按鈕,無需任何容器(例如:組)

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

希望能幫助到某人!

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

這就是整個bg是可點擊的

SwiftUI 顏色

從 iOS v13 及更高版本開始,當您使用顏色時,您應該考慮 Light 和 Dark 模式。

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

例如,黑暗模式下的 .black 將是不可見的(黑底黑字)。 您可以使用系統顏色作為變體。 例如UIColor.label

同樣在 SwiftUI 中,如果您使用 .buttonStyle 並想要更改背景顏色,您將使用 .tint,而不是 .background。 例如,您可以通過以下方式將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