如何解决SwiftUI List -> ForEach -> Item 是一个 let,所以我不能改变一个值
如果我点击列表中的一个项目(只需切换它),我想更改“点击”的值... 但是这个错误来了:“不能在不可变值上使用变异成员:'item'是一个'let'常量” 我理解正确,我认为但我不知道如何修复那个“项目”不再允许 即使我在结构中创建一个变异函数来改变值也不起作用
感谢您的帮助!
struct Gamemode: Identifiable {
var id: Int
var name: String
var clicked: Bool
}
struct ContentView: View {
@State private var gamemodes: [Gamemode] = [
Gamemode(id: 1,name: "example text",clicked: false),Gamemode(id: 2,name: "second example text",Gamemode(id: 3,name: "third example text",Gamemode(id: 4,name: "fourth example text",clicked: false)
]
var body: some View {
List {
ForEach(gamemodes) { item in
vstack {
Text("Selection \(item.id)")
Text("\(item.name)")
}
.background(Color((item.clicked) ? .blue : .yellow))
.onTapGesture {
item.clicked.toggle()
}
}
}
}
}
解决方法
我不知道这是否是最好的解决方案,但也许是:
import SwiftUI
struct Gamemode: Identifiable {
var id: Int
var name: String
var clicked: Bool
}
struct ContentView: View {
@State private var gamemodes: [Gamemode] = [
Gamemode(id: 1,name: "example text",clicked: false),Gamemode(id: 2,name: "second example text",Gamemode(id: 3,name: "third example text",Gamemode(id: 4,name: "fourth example text",clicked: false)
]
var body: some View {
List {
ForEach(0..<gamemodes.count) { index in
VStack {
Text("Selection \(gamemodes[index].id)")
Text("\(gamemodes[index].name)")
}
.background(Color((gamemodes[index].clicked) ? .blue : .yellow))
.onTapGesture {
gamemodes[index].clicked.toggle()
}
}
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。