1

Hello exist a easy way to put values inside UserDefaults as EnvironmentObject to be displayed in other views? Something like set username in the SettingsView and be displayed in the DashboardView. Thx a lot

1 Answer 1

1

Finally find it How do I use UserDefaults with SwiftUI?

The answer based only for Bool. Her is the solution to do it with String too.

The ContentView set up with a TabView:

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            TabView{
                Dashboard(userName: UserName())
                    .tabItem({
                        Image(systemName: "rectangle.3.offgrid")
                        Text("Dashboard")
                    })
                Settings()
                    .tabItem({
                        Image(systemName: "gear")
                        Text("Einstellungen")
                    })
            }
        }
    }
}

#if DEBUG
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
#endif

UserSettings for Bool and UserName for String

import SwiftUI
import Combine


final class UserSettings: ObservableObject {

    let objectWillChange = PassthroughSubject<Void, Never>()

    @UserDefault("ShowOnStart", defaultValue: true)
    var showOnStart: Bool {
        willSet {
            objectWillChange.send()
        }
    }
}

final class UserName: ObservableObject {

    let objectWillChange = PassthroughSubject<Void, Never>()

    @UserDefault("userName", defaultValue: "UknowName")
    var userNameSet: String {
        willSet {
            objectWillChange.send()
        }
    }
}

Property Wrapper UserDefaults used in UserSettings and UserName class

@propertyWrapper
struct UserDefault<T> {
    let key: String
    let defaultValue: T

    init(_ key: String, defaultValue: T) {
        self.key = key
        self.defaultValue = defaultValue
    }

    var wrappedValue: T {
        get {
            return UserDefaults.standard.object(forKey: key) as? T ?? defaultValue
        }
        set {
            UserDefaults.standard.set(newValue, forKey: key)
        }
    }
}

First view Dashboard there presented the changes that were made in the settings view

import SwiftUI

struct Dashboard: View {
    @ObservedObject var settings = UserSettings()
    @ObservedObject var userName = UserName()
    var body: some View {
        VStack{
            Text("hallo")

            ExtractedViewName(userName: userName)
                ExtractedView(settings: settings)

        }
    }
}

struct Dashboard_Previews: PreviewProvider {
    static var previews: some View {
        Dashboard(userName: UserName())
    }
}

struct ExtractedView: View {
    @ObservedObject var settings : UserSettings
    var body: some View {
        VStack{
        if settings.showOnStart{
        Text("Welcome")
        }
        }
    }
}

struct ExtractedViewName: View {
    @ObservedObject var userName : UserName
    var body: some View {
        Text("Test One: \(userName.userNameSet)")
    }
}

Second view Settings there set the changes that display in the Dashboard view

import SwiftUI

struct Settings: View {
   @ObservedObject var settings = UserSettings()
@ObservedObject var userName = UserName()
    @State private var userTextfield = ""
    var body: some View {
        VStack {
            Toggle(isOn: $settings.showOnStart) {
                Text("Show welcome text")
            }
            TextField("Name", text: $userTextfield){
                self.userName.userNameSet = self.userTextfield
            }
            Button(action: {
                print("\(self.userName.userNameSet)")
            }) {
                Text("Button")
            }
        }
        }
}

struct Settings_Previews: PreviewProvider {
    static var previews: some View {
        Settings()
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.