binding swiftui in swift

To bind data in SwiftUI, you need to understand the concepts of "observed objects" and "state objects".

  1. Observed Objects: An observed object is a SwiftUI property wrapper that allows the view to observe changes in the underlying object. You can use this property wrapper on your class instances to make sure that any changes that happen in the class are immediately reflected in the views that use those instances.
main.swift
class DataViewModel: ObservableObject {
  @Published var title: String = ""
  //add more properties and methods
}

struct ContentView: View {
  @ObservedObject var data = DataViewModel()
  var body: some View {
    Text(data.title)
  }
}
238 chars
12 lines
  1. State Objects: State objects are another property wrapper that SwiftUI provides to manage the state of a view.
main.swift
struct ContentView: View {
  @State var title: String = ""
  var body: some View {
    TextField("Enter Title", text: $title)
    Text(title)
  }
}
148 chars
8 lines

Both ObservedObject and StateObject ensure that changes made to the objects are immediately reflected in the views. The primary difference between ObservedObject and StateObject is that the former is used when the object is managed outside of the view, while the latter is used when the object is owned by the view and is specific to that view.

To bind data in SwiftUI, you can use either observed objects or state objects depending on your use case.

related categories

gistlibby LogSnag