Skip to content

Instantly share code, notes, and snippets.

@davidsteppenbeck
Created August 16, 2023 18:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidsteppenbeck/c70048d908d21ad728110d876ff5c10b to your computer and use it in GitHub Desktop.
Save davidsteppenbeck/c70048d908d21ad728110d876ff5c10b to your computer and use it in GitHub Desktop.
Examples of applying `Bindable` from environment observables in SwiftUI views in iOS 17
import SwiftUI
@Observable class ViewModel {
var isOn: Bool
var text: String
init(isOn: Bool = false, text: String = "default") {
self.isOn = isOn
self.text = text
}
}
struct StateView: View {
@State var model = ViewModel(isOn: true, text: "some model text")
var body: some View {
BindableModelView1().environment(model)
Divider()
BindableModelView2().environment(model)
}
}
struct BindableModelView1: View {
@Environment(ViewModel.self) var model
private var bindable: Bindable<ViewModel> {
Bindable(model)
}
var body: some View {
VStack {
Text("Bindable Model View 1").bold().foregroundStyle(Color.primary)
Text(model.text)
Text("on: \(model.isOn.description)")
Toggle("toggle", isOn: bindable.isOn)
TextField("text field", text: bindable.text)
}
.foregroundStyle(model.isOn ? .green : .red)
.padding()
}
}
struct BindableModelView2: View {
@Environment(ViewModel.self) var model
var body: some View {
VStack {
Text("Bindable Model View 2").bold().foregroundStyle(Color.primary)
Text(model.text)
Text("on: \(model.isOn.description)")
Toggle("toggle", isOn: Bindable(model).isOn)
TextField("text field", text: Bindable(model).text)
}
.foregroundStyle(model.isOn ? .green : .red)
.padding()
}
}
#Preview {
StateView()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment