我有一个动态的按钮数组。按下一个按钮,它的图片会改变,其余的不会改变。但是当我点击任何一个按钮时,所有元素的图片也会改变。
如何做到当你点击一个按钮时,只有这个按钮的图片改变,其余的不改变?谢谢你
import SwiftUI
struct Result {
var id = UUID()
var score: Int
}
struct DynamicButtonsView: View {
let results = [Result(score: 8), Result(score: 5), Result(score: 10), Result(score: 12) , Result(score: 33)]
@State var imageName: String = "UnselectedSircle"
var body: some View {
VStack {
ForEach(results, id:(.id)) { result in
Button(action: {
print(result.score)
print(imageName)
self.imageName = "SelectedCircle"
}, label: {
Image(imageName)
.resizable()
.scaledToFill()
Text("(result.score)")
}).frame(width: 50, height: 50, alignment: .center)
}
}
}
}
struct DynamicButtonsView_Previews: PreviewProvider {
static var previews: some View {
DynamicButtonsView()
}
}
下面的代码在iPhone 6s (iOS 14.4)上进行了测试
struct Result {
var id = UUID()
var score: Int
var isSected:Bool = false
}
struct test: View {
@State private var myList = [Result(score: 23),Result(score: 33),Result(score: 28),Result(score: 11)]
var body: some View {
List(myList,id:.id){item in
HStack{
Text("(item.score)")
Spacer()
Button(action: {
guard let index = myList.firstIndex(where: {$0.id == item.id})else{
return
}
myList[index].isSected.toggle()
}, label: {
Image(systemName:item.isSected ? "circle.fill" : "circle")
})
}
}
}
}
那么,如果我没理解错的话,你是想让任何点击过的按钮的图片发生变化而没有点击过的按钮不发生变化吗?基本上代表了某种"选择状态"按钮的位置?
基本上,你必须为你想要看到的状态建模。如果只有视图需要了解选择状态,则可以将其建模为一组uid,如下所示:
struct DynamicButtonsView: View {
let results = [Result(score: 8), Result(score: 5), Result(score: 10), Result(score: 12) , Result(score: 33)]
@State var selectedIDs = Set<UUID>()
@State var imageName: String = "checkmark.circle"
var body: some View {
VStack {
ForEach(results, id:(.id)) { result in
Button(action: {
if selectedIDs.contains(result.id) {
selectedIDs.remove(result.id)
} else {
selectedIDs.insert(result.id)
}
print(result.score)
print(imageName)
}, label: {
Image(systemName: selectedIDs.contains(result.id) ? "checkmark.circle.fill" : "checkmark.circle")
.resizable()
.scaledToFill()
Text("(result.score)")
}).frame(width: 50, height: 50, alignment: .center)
}
}
}
}
注意:我改变了图像纯粹是因为我没有你的资产目录,所以我使用了一些随机图像从SFSymbols为我的例子。