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

后端 未结 4 997
一生所求
一生所求 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:29

    I've found this works: In your AppState, when you add a project, observe its changes:

    import Combine
    
    class AppState: ObservableObject {
      @Published var projects: [Project]
      var futures = Set()
    
      func addProject(project: Project) {
        project.objectWillChange
          .sink {_ in
            self.objectWillChange.send()
          }
         .store(in: &futures)
      }
    
      ...
    }
    

    If you ever need to create a binding for a project var in your outer view, do it like this:

    func titleBinding(forProject project: Project) -> Binding {
        Binding {
            project.title
        } set: { newValue in
            project.title = newValue
        }
    }
    

    You shouldn't need it if you are passing the project into another view, though.

提交回复
热议问题