0

I am using SwiftUI on the Apple Watch and trying to use @ObservableObject, @ObservedObject, and @Binding correctly. I'm updating a value in a DetailView, and I want to have it reflected locally, as well as have the data changed globally. The code below works, but I am using a kludge to force the DetailView to redraw itself:

Is there a better way?

-------------- ContentView.swift ---------------

import Combine
import SwiftUI

struct person: Identifiable {
    var id:Int = 0
    var name:String
    init( id: Int, name:String) {
        self.id = id
        self.name = name
    }
}

class AppData:  ObservableObject {
    @Published var people:[person] = [person(id:0, name:"John"),
                                      person(id:1, name:"Bret"),
                                      person(id:2,name:"Sue"),
                                      person(id:3,name:"Amy")]
}

var gAppData = AppData()

struct ContentView: View {
    @ObservedObject var model:AppData
    var body: some View {
        List( model.people.indices ){ index in
            NavigationLink(destination: DetailView(person:self.$model.people[index])) { Text(self.model.people[index].name) }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView(model:gAppData)
    }
}

-------------- DetailView.swift ---------------

import SwiftUI

struct DetailView: View {
    @Binding var person: person

    // Created an unnecessary var to force a redreaw of the view
    @State var doRedraw:Bool = true

    var body: some View {
        VStack(){
                Text(person.name)
            Button(action:{ self.person.name = "Bob"; self.doRedraw = false }) {
                    Text("Set Name to Bob")
                }
            }

        }
    }

struct DestView_Previews: PreviewProvider {
    static var previews: some View {
        DetailView(person:.constant(person( id:0, name:"John"))) // what does ".constant" actually do?
    }
}
jbsman
  • 1
  • 1

1 Answers1

0

The problem here is because your view redraws only when you changes the @State or @Binding variable. Here you do not change the Person variable, but its property, which should not affect the user interface (because you didn't say to do this). I changed your code for a little for showing how to achieve this effect, you can go ahead from this point. You need to remember, what exactly affect UI:

class Person: Identifiable, ObservableObject { // better to assign struct/class names using UpperCamelCase

    @Published var name:String // now change of this variable will affect UI
    var id:Int = 0

    init( id: Int, name:String) {
        self.id = id
        self.name = name
    }

}

// changes in DetailView
struct DetailView: View {

    @EnvironmentObject var person: Person

    var body: some View {
        VStack(){
            Text(person.name)
            Button(action:{ self.person.name = "Bob" }) {
                Text("Set Name to Bob")
            }
        }

    }
}

// preview
struct DetailViewWithoutGlobalVar_Previews: PreviewProvider {
    static var previews: some View {
        DetailView()
            .environmentObject(Person(id: 1, name: "John"))
    }
}

update: full code for List and Detail

import SwiftUI

class Person: Identifiable, ObservableObject { // better to assign type names using UpperCamelCase

    @Published var name: String //{
    var id: Int = 0

    init( id: Int, name:String) {
        self.id = id
        self.name = name
    }

    func changeName(_ newName: String) {
        self.name = newName
    }

}

class AppData: ObservableObject {
    @Published var people: [Person] = [Person(id:0, name:"John"),
                                      Person(id:1, name:"Bret"),
                                      Person(id:2,name:"Sue"),
                                      Person(id:3,name:"Amy")]
}

struct ContentViewWithoutGlobalVar: View {

    @EnvironmentObject var model: AppData

    var body: some View {
        NavigationView { // you forget something to navigate between views
            List(model.people.indices) { index in
                NavigationLink(destination: DetailView()
                    .environmentObject(self.model.people[index])) {
                        PersonRow(person: self.$model.people[index])
                }
            }
        }

    }

}

struct PersonRow: View {

    @Binding var person: Person // this struct will see changes in Person and show them

    var body: some View {
        Text(person.name)
    }

}

struct DetailView: View {

    @EnvironmentObject var person: Person

    var body: some View {
        VStack(){
            Text(self.person.name)
            Button(action:{ self.person.changeName("Bob") }) {
                Text("Set Name to Bob")
            }
        }

    }
}

struct ContentViewWithoutGlobalVar_Previews: PreviewProvider {
    static var previews: some View {
        Group {
            ContentViewWithoutGlobalVar()
                .environmentObject(AppData())

            DetailView()
                .environmentObject(Person(id: 0, name: "John"))
        }
    }
}
Hrabovskyi Oleksandr
  • 3,070
  • 2
  • 17
  • 36