Connect data to show in views with data defined in Model.
Model class:
Swift
12345
classBook:ObservableObject{/// @Published: Once title changed, Views related with Book refreshed./// @Published works when this class is an ObservableObject@Publishedvartitle="Great Expectations"}
SwiftUI codes:
Swift
1 2 3 4 5 6 7 8 910111213
structLibraryView:View{@StateObjectvarbook=Book()// Book is a class conforming to ObservableObject. Only instantiating uses `@StateObject`varbody:someView{BookView(book:book)}}structBookView:View{@ObservedObjectvarbook:Book// Here book is not an instance of Model. So yse @ObservedObject// ...}
Save your time to pass arguments again and again if there are plenty of layers.
Swift
1 2 3 4 5 6 7 8 91011
@mainstructBookReader:App{@StateObjectvarlibrary=Library()// initiate ObservableObject with `@StateObject`varbody:someScene{WindowGroup{LibraryView().environmentObject(library)// Here pass `library` to all sub-views of LibraryView().}}}
Swift
12345
structLibraryView:View{@EnvironmentObjectvarlibrary:Library// Get that EnvironmentObject// ...}
structPlayerView:View{letepisode:Episode@StateprivatevarisPlaying:Bool=falsevarbody:someView{VStack{Text(episode.title)Text(episode.showTitle)PlayButton(isPlaying:$isPlaying)// Pass a binding.}}}
Swift
1 2 3 4 5 6 7 8 91011
structPlayButton:View{@BindingvarisPlaying:Boolvarbody:someView{Button(action:{self.isPlaying.toggle()// change isPlaying in sub-view. So use @Binding}){Image(systemName:isPlaying?"pause.circle":"play.circle")}}}