无法通过 ForEach 按钮更新 @State 变量(Int Counter)?
Posted
技术标签:
【中文标题】无法通过 ForEach 按钮更新 @State 变量(Int Counter)?【英文标题】:Update @State variable (Int Counter) through ForEach button not possible? 【发布时间】:2019-07-08 11:27:08 【问题描述】:尝试通过迭代 ForEach 按钮来更新计数器,但在 Xcode 11 中收到以下错误:
无法将 >'ForEach, >_ModifiedContent)>>, >PaddingLayout>>' 类型的值转换为闭包结果类型 ''
已尝试添加@State,但仍无法更新 var characterList 中的计数
import SwiftUI
struct CharacterSelection:Identifiable
var id: Int
var name : String
var count: Int
import SwiftUI
struct ContentView : View
@State var charactersList = [
CharacterSelection(id: 0, name: "Witch", count: 0),
CharacterSelection(id: 1, name: "Seer", count: 1),
CharacterSelection(id: 2, name: "Hunter", count: 0),
CharacterSelection(id: 3, name: "Knight", count: 0)
]
var body: some View
VStack(alignment:.leading)
ForEach(charactersList.identified(by: \.id)) character in
HStack
Text(character.name)
Spacer()
Text("\(character.count)
Button(action: character.count += 1 )
Text("Button")
.padding(10)
点击按钮时,var CharacterList 中相应索引的计数应为 += 1。
【问题讨论】:
【参考方案1】:请注意,Arrays 和 CharacterSelection 都是 Value 类型,而不是 Reference 类型。如果您不知道区别,请查看此页面:https://developer.apple.com/swift/blog/?id=10
为了让你的代码正常工作,你可以这样重写它:
struct ContentView : View
@State var charactersList = [
CharacterSelection(id: 0, name: "Witch", count: 0),
CharacterSelection(id: 1, name: "Seer", count: 1),
CharacterSelection(id: 2, name: "Hunter", count: 0),
CharacterSelection(id: 3, name: "Knight", count: 0)
]
var body: some View
VStack(alignment:.leading)
ForEach(0..<charactersList.count) i in
HStack
Text(self.charactersList[i].name)
Spacer()
Text("\(self.charactersList[i].count)")
Button(action: self.charactersList[i].count += 1 )
Text("Button")
.padding(10)
Button(action:
self.charactersList.append(CharacterSelection(id: self.charactersList.count, name: "something", count: 0))
, label:
Text("Add CharacterSelection")
)
【讨论】:
感谢分享这篇文章 - 有助于理解很多!这按预期工作。但在这种情况下,我应该如何附加到 CharacterSelection,比如将第 5 项添加到数组中? 我更新了示例,添加了一个用于追加新行的按钮。 有趣的是我从来没有想过——感谢您的指导!我会把这个传下去! :)以上是关于无法通过 ForEach 按钮更新 @State 变量(Int Counter)?的主要内容,如果未能解决你的问题,请参考以下文章