SwiftUI: How to iterate over an array of bindable objects?

后端 未结 4 1049
一生所求
一生所求 2021-02-05 14:51

I\'m trying to learn SwiftUI, and how bindings work.

I have this code that works, that shows a list of projects. When one project is tapped, a binding to that project is

4条回答
  •  半阙折子戏
    2021-02-05 15:13

    I'm sort of stuck on the same issue you are, and I found a partial solution. But first I should point out that iterating over the index with ForEach(0.. is not a good idea because index is an Int, which does not conform to Identifiable. Because of that, the UI will not update when your array changes, and you'll see a warning in the console.

    My solution directly accesses the state.projects array when creating ProjectView and using firstIndex(of:) to get a bindable form of the project element. It's kind of icky but it's as far as I could get to making it more SwiftUI-y.

    ForEach(state.projects) { project in
      NavigationLink(destination: ProjectView(project: self.$state.projects[self.state.projects.firstIndex(of: project)!]))) {
        Text(project.title)
      }
    }
    

提交回复
热议问题