|
| 1 | +#if canImport(AndroidSwiftUI) |
| 2 | +import AndroidSwiftUI |
| 3 | +#else |
| 4 | +import SwiftUI |
| 5 | +#endif |
| 6 | + |
| 7 | +import Observation |
| 8 | + |
| 9 | +@Observable |
| 10 | +final class ProfileModel { |
| 11 | + var name = "" |
| 12 | + var subscribed = false |
| 13 | + var volume = 0.5 |
| 14 | +} |
| 15 | + |
| 16 | +struct BindablePlayground: View { |
| 17 | + @State private var model = ProfileModel() |
| 18 | + var body: some View { |
| 19 | + ScrollView { |
| 20 | + BindableForm(model: model) |
| 21 | + } |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +/// `@Bindable` takes the model by reference and projects `$model.property` |
| 26 | +/// bindings into it; writing a bound control mutates the observable, which |
| 27 | +/// re-evaluates the views that read it. |
| 28 | +struct BindableForm: View { |
| 29 | + @Bindable var model: ProfileModel |
| 30 | + var body: some View { |
| 31 | + VStack(alignment: .leading, spacing: 0) { |
| 32 | + Example("Bound TextField") { |
| 33 | + VStack(alignment: .leading, spacing: 8) { |
| 34 | + TextField("Name", text: $model.name) |
| 35 | + Text(model.name.isEmpty ? "No name yet" : "Hello, \(model.name)") |
| 36 | + } |
| 37 | + } |
| 38 | + Example("Bound Toggle") { |
| 39 | + VStack(alignment: .leading, spacing: 8) { |
| 40 | + Toggle("Subscribed", isOn: $model.subscribed) |
| 41 | + Text(model.subscribed ? "Subscribed" : "Not subscribed") |
| 42 | + } |
| 43 | + } |
| 44 | + Example("Bound Slider") { |
| 45 | + VStack(alignment: .leading, spacing: 8) { |
| 46 | + Slider(value: $model.volume, in: 0...1) |
| 47 | + Text("Volume: \(Int(model.volume * 100))%") |
| 48 | + } |
| 49 | + } |
| 50 | + Example("Shared model") { |
| 51 | + Text("All three controls above bind into one @Observable model.") |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | +} |
0 commit comments