无法通过ForEach按钮更新@State变量(整数计数器)吗?

时间:2019-07-08 11:27:08

标签: foreach swiftui ios13

尝试通过遍历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 个答案:

答案 0 :(得分:0)

请注意,数组和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")
            })

        }
    }
}