[英]SwiftUI - How to change the colour of all other buttons when pressing on button?
在我的代碼下面,我有一個設置,其中有 4 個按鈕,每次按下按鈕時,它都充當切換按鈕(如單選按鈕)。 我想要實現的是在按下其中一個按鈕時將所有其他按鈕變為灰色。 一次只能有一個按鈕為綠色或活動狀態。
struct hzButton: View {
var text: String
@State var didTap: Bool
var body: some View {
Button(action: {
if self.didTap == true{
self.didTap = false
}else{
self.didTap = true
}
selectFreq(frequency: self.text)
}) {
Text(text)
.font(.body)
.fontWeight(.semibold)
.foregroundColor(Color.white)
.multilineTextAlignment(.center)
.padding(.all)
.background(didTap ? Color.green : Color.gray)
.cornerRadius(6.0)
}
.frame(width: nil)
}
}
struct Row: Identifiable {
let id = UUID()
let headline: String
let numbers: [String]
}
struct ContentView: View {
var rows = [
Row(headline: "", numbers: ["250","500","750","1000"]),
]
var body: some View {
HStack {
ForEach(rows) { row in
HStack {
ForEach(row.numbers, id: \.self) { text in
hzButton(text: text, didTap: false)
}
}
}
}
}
}
在 SwiftUI 中,一切都由 state 更改觸發。 要實現單選按鈕樣式更改,您需要執行以下操作:
struct MyRadioButton: View {
let id: Int
@Binding var currentlySelectedId: Int
var body: some View {
Button(action: { self.currentlySelectedId = self.id }, label: { Text("Tap Me!") })
.foregroundColor(id == currentlySelectedId ? .green : .red)
}
}
struct MyRadioButtons: View {
@State var currentlySelectedId: Int = 0
var body: some View {
VStack {
MyRadioButton(id: 1, currentlySelectedId: $currentlySelectedId)
MyRadioButton(id: 2, currentlySelectedId: $currentlySelectedId)
MyRadioButton(id: 3, currentlySelectedId: $currentlySelectedId)
MyRadioButton(id: 4, currentlySelectedId: $currentlySelectedId)
}
}
}
當共享的 currentSelectedId 更改時,依賴於 state 的所有按鈕將相應更新。
不要將其視為 4 個單獨的按鈕,每個按鈕都有自己的開/關 state,而是將整個組視為一個整體,以及它們如何代表單個電流值 state。 然后,當每個按鈕在確定其背景顏色時,它可以考慮“我的值是否與當前選擇的值匹配?”。 因此,不要在點擊按鈕時切換 boolean,而是讓按鈕使用自己的值更新當前選定的值(在組中的所有按鈕之間共享)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.