【发布时间】:2021-08-19 09:30:15
【问题描述】:
【问题讨论】:
-
用例不清楚。如果将系统首选项中的强调色更改为颜色,则会自动启动视图更新,例如。在
Text("Demo").foregroundColor(.accentColor).
标签: swift macos swiftui colors appearance
【问题讨论】:
Text("Demo").foregroundColor(.accentColor).
标签: swift macos swiftui colors appearance
一种可能的方法是通过AppStorage观察者使用NSUserDefaults中的更改,例如
struct ContentView: View {
@AppStorage("AppleAccentColor") var appleAccentColor: Int = 0
var body: some View {
Text("Hello world!")
.foregroundColor(.accentColor) // << updated automatically
.onChange(of: appleAccentColor) { _ in
print("Side-effect is here")
// also can be read via NSColor.controlAccentColor
}
}
}
使用 Xcode 15 / macOS 11.5 测试
【讨论】:
这是一种可能更灵活的方法,例如,您可以将其用于您的视图模型:
import Combine
class SomeClass {
var cancellable: AnyCancellable?
init() {
cancellable = NSApp.publisher(for: \.effectiveAppearance).sink { appearance in
print(appearance.name.rawValue)
}
}
}
您可能必须确保调用 cancellable?.cancel() 以便可以取消初始化对象。
【讨论】: