SwiftUI Codes
Best SwiftUI Code Warehouse

Lesson 6: Data Binding and State Management

Objective:

Understand data binding and state management in SwiftUI.

Content:

1. @State

The @State property wrapper is used for local state management within a view.

Local State Management:

@State private var count = 0

var body: some View {
    VStack {
        Text("Count: \(count)")
        Button("Increment") {
            count += 1
        }
    }
}

Explanation:

2. @Binding

The @Binding property wrapper allows a child view to read and write a value owned by a parent view.

Passing State to Child Views:

struct ParentView: View {
    @State private var count = 0

    var body: some View {
        VStack {
            Text("Count: \(count)")
            ChildView(count: $count)
        }
    }
}

struct ChildView: View {
    @Binding var count: Int

    var body: some View {
        Button("Increment in Child") {
            count += 1
        }
    }
}

Explanation:

3. @ObservedObject and ObservableObject

The @ObservedObject property wrapper subscribes to an ObservableObject and updates the view when the object's data changes.

Managing State with @ObservedObject:

class Counter: ObservableObject {
    @Published var count = 0
}

struct ContentView: View {
    @ObservedObject var counter = Counter()

    var body: some View {
        VStack {
            Text("Count: \(counter.count)")
            Button("Increment") {
                counter.count += 1
            }
        }
    }
}

Explanation:

4. @EnvironmentObject

The @EnvironmentObject property wrapper allows views to share an object that is accessible across the entire view hierarchy.

Shared State Across Views:

class Settings: ObservableObject {
    @Published var isDarkMode = false
}

struct ContentView: View {
    @EnvironmentObject var settings: Settings

    var body: some View {
        Toggle("Dark Mode", isOn: $settings.isDarkMode)
    }
}

Explanation:

Lesson 7: Navigation and Transitions