【发布时间】:2021-12-29 10:23:34
【问题描述】:
设置:
斯威夫特 5.5, Xcode 13.2
这个话题遍布网络,这里是one of them。好吧,我的应用有三个选项:
- 开:无论系统设置如何,都使用暗模式
- 关闭:无论系统设置如何,都使用灯光模式
- 系统:使用系统默认值(浅色或深色)
我有一个简单的类可以切换三个:
import SwiftUI
class Utilities: ObservableObject {
// The default is to use the system's default.
@AppStorage("theme") var theme: String = ""
var userInterfaceStyle: ColorScheme? = .dark
func overrideDisplayMode() {
var userInterfaceStyle: UIUserInterfaceStyle
if theme == "On" {
userInterfaceStyle = .dark
} else if theme == "Off" {
userInterfaceStyle = .light
} else {
// System
userInterfaceStyle = .unspecified
}
let scenes = UIApplication.shared.connectedScenes
let windowScene = scenes.first as? UIWindowScene
let window = windowScene?.windows.first
window?.overrideUserInterfaceStyle = userInterfaceStyle
}
}
它是如何更新的(减去按钮功能等):
@main
struct MainApp: App {
@StateObject var utilities = Utilities()
var body: some Scene {
WindowGroup {
ContentView()
.onChange(of: utilities.theme, perform: { _ in
utilities.overrideDisplayMode()
})
// Ensures the theme is set when app first loads
.onAppear(perform: {
utilities.overrideDisplayMode()
}
}
}
}
这很好用:主题化。唯一的问题是状态栏。每当我 overrideUserInterfaceStyle 或 theme 更改时,我都想更改状态栏颜色。我怎样才能通过这种设置实现这一点?
【问题讨论】:
标签: swiftui