SwiftUI List -> ForEach -> Item 是一个让,所以我不能改变一个值
Posted
技术标签:
【中文标题】SwiftUI List -> ForEach -> Item 是一个让,所以我不能改变一个值【英文标题】:SwiftUI List -> ForEach -> Item is a let, so i can't change a value 【发布时间】:2021-05-16 09:39:00 【问题描述】:如果我点击列表中的一个项目(只需切换它),我想更改“点击”的值...... 但是这个错误来了:“不能在不可变值上使用变异成员:'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", clicked: false),
Gamemode(id: 3, name: "third example text", clicked: false),
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()
【问题讨论】:
【参考方案1】:我不知道这是否是最好的解决方案,但也许是这样:
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", clicked: false),
Gamemode(id: 3, name: "third example text", clicked: false),
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()
【讨论】:
以上是关于SwiftUI List -> ForEach -> Item 是一个让,所以我不能改变一个值的主要内容,如果未能解决你的问题,请参考以下文章
为啥 swipeActions 修饰符不能直接与 List 容器一起使用? #SwiftUI