我有一個我無法解決的問題。當用戶點擊它時,我想更改其中一個按鈕的背景顏色。
所以我做了這個代碼
ForEach(allWords, id: \.self) { myRow in
Button{
if (self.didTap == true){
self.didTap = false
}
else {
self.didTap = true
}
self.variableTitle = myRow
isNight.toggle()
} label:{
ULD(title: myRow, textColor: .black, backgroundColor: didTap ? .red : .green)
}
我在 allWords 和 myRow 中檢索單詞串列的位置每次都包含我在按鈕上的標題。
問題是當我點擊一個按鈕時,所有按鈕都會改變顏色,但我只想改變我點擊的一個按鈕的顏色。
你能幫我解決這個問題嗎?
謝謝
uj5u.com熱心網友回復:
您需要didTap為每個Button. 這可以通過將按鈕移動到單獨的視圖來實作。
您可以創建此視圖:
struct MyButton: View {
@State private var didTap = false // This will change the color
let myRow: String // I'm assuming it's a String, otherwise use the correct type
@Binding var isNight: Bool // This will change the variable in the parent view
@Binding var variableTitle: String // This will change the variable in the parent view (always assuming it's a String)
var body: some View {
Button{
didTap.toggle()
variableTitle = myRow
isNight.toggle()
} label:{
ULD(title: myRow, textColor: .black, backgroundColor: didTap ? .red : .green)
}
}
}
然后,在您的父視圖中,只需按照以下示例呼叫它。請記住,isNight并且兩者都必須是父視圖中的variableTitle 變數@State。
ForEach(allWords, id: \.self) { myRow in
MyButton(myRow: myRow, isNight: $isNight, variableTitle: $variableTitle)
}
uj5u.com熱心網友回復:
我希望這能幫到您,
struct ContentView: View {
@State var allWords = ["Button1","Button2","Button3","Button4"]
@State var allSelectedWords = Set<String>()
var body: some View {
ForEach(allWords, id: \.self) { myRow in
if #available(iOS 15.0, *) {
Button(action:{
if allSelectedWords.contains(myRow) {
allSelectedWords.remove(myRow)
} else {
allSelectedWords.removeAll()
allSelectedWords.insert(myRow)
}
}){
Text(myRow)
.foregroundColor(.black)
.background(allSelectedWords.contains(myRow) ? .red : .green)
}
} else {
// Fallback on earlier versions
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/457375.html
