這個問題在這里已經有了答案: 如何為 SwiftUI 中的按鈕陣列的 ForEach 回圈內的任何特定按鈕添加修飾符? (2 個回答) 3天前關閉。
我想從按鈕堆疊中為特定的點擊按鈕設定影片。不幸的是withAnimation{}應用于由 FOREACH 回圈創建的所有按鈕,實際上點擊了哪個按鈕沒有區別。您能否推薦解決問題的正確方法?這是我的代碼:
import SwiftUI
struct ContentView: View {
@State private var buttonBackgroundColorRed = false
var body: some View {
VStack {
ForEach(1..<4) {num in
Button {
withAnimation {
buttonBackgroundColorRed.toggle()
}
} label: {
Text("Button \(num)")
}
.padding(10)
.background(buttonBackgroundColorRed ? .red : .blue)
.foregroundColor(.white)
.padding()
}
}
}
}
uj5u.com熱心網友回復:
這也是可能的,但將ForEach行提取到具有自己狀態的獨立視圖中更簡單
struct ContentView: View {
struct Row: View {
let num: Int
@State private var buttonBackgroundColorRed = false
var body: some View {
Button {
withAnimation {
buttonBackgroundColorRed.toggle()
}
} label: {
Text("Button \(num)")
}
.padding(10)
.background(buttonBackgroundColorRed ? .red : .blue)
.foregroundColor(.white)
.padding()
}
}
var body: some View {
VStack {
ForEach(1..<4) {num in
Row(num: num)
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/488238.html
上一篇:洗掉HTML/CSS中的頁腳
下一篇:CSS/JS中的影片
