我们以暗黑模式的适配来实践EnvironmentObject
暗黑模式适配
定义AppSetting
,设置 @Published var darkModeSettings
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class AppSetting: ObservableObject { @Published var darkModeSettings: Int = UserDefaults.standard.integer(forKey: "darkMode") { didSet { UserDefaults.standard.set(self.darkModeSettings, forKey: "darkMode") let scenes = UIApplication.shared.connectedScenes let windowScene = scenes.first as? UIWindowScene let window = windowScene?.windows.first switch self.darkModeSettings { case 0: window?.overrideUserInterfaceStyle = .unspecified case 1: window?.overrideUserInterfaceStyle = .light case 2: window?.overrideUserInterfaceStyle = .dark default: window?.overrideUserInterfaceStyle = .unspecified } } } }
|
传入 .environmentObject(AppSetting())
1 2 3 4 5 6 7 8
| @main struct tableViewApp: App { var body: some Scene { WindowGroup { ContentView().environmentObject(AppSetting()) } } }
|
使用@EnvironmentObject
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| struct SettingsView: View { @EnvironmentObject var appSettings: AppSetting var body: some View { NavigationStack { List { Section { HStack{ Button { appSettings.darkModeSettings = 0 } label: { Text("跟随系统").foregroundColor(.primary) } Spacer() if(appSettings.darkModeSettings == 0){ Image(systemName: "checkmark") } } HStack{ Button { appSettings.darkModeSettings = 1 } label: { Text("白").foregroundColor(.primary) } Spacer() if(appSettings.darkModeSettings == 1){ Image(systemName: "checkmark") } } HStack{ Button { appSettings.darkModeSettings = 2 } label: { Text("暗黑").foregroundColor(.primary) } Spacer() if(appSettings.darkModeSettings == 2){ Image(systemName: "checkmark") } } } header: { Text("主题设置") .textCase(nil) } } .listStyle(.insetGrouped) .navigationTitle("设置") } } }
|
相关链接阅读
SwiftUI: 全局状态管理