SwiftUI: Sharing AppStorage across the whole app

Published by malhal on

Sharing @AppStorage without having to pass it into every feature of the app is simply done in the same way it’s done for anything else you want to share: EnvironmentKey. It lets you share a source of truth into a View hierarchy without needing to pass it into every View. Use it with @AppStorage as follows:

import SwiftUI

extension EnvironmentValues {
    // if you need read/write
    @Entry var appStorageToggle: Binding<Bool> = .constant(false)
}

struct StorageTest {

    struct ContentView: View {
        
        @AppStorage("Toggle") var isOn = false

        var body: some View {
            NavigationStack {
                List {
                    ChildView()
                }
            }
            .environment(\.storageTestMyCustomValueBinding, $isOn)
        }
    }
    
    struct ChildView: View {
        @Environment(\.appStorageToggle) var _isOn
        
        var body: some View {
            @Binding(projectedValue: _isOn) var isOn

            Toggle("Toggle", isOn: $isOn)

            if isOn == true {
                Text("Row")
            }
        }
    }
}
Categories: SwiftUI