【问题标题】:Swift ui macOS event detect change accent colorSwift ui macOS 事件检测更改强调色
【发布时间】:2021-08-19 09:30:15
【问题描述】:

通用设置中是否有事件判断强调色类型的变化?

【问题讨论】:

  • 用例不清楚。如果将系统首选项中的强调色更改为颜色,则会自动启动视图更新,例如。在Text("Demo").foregroundColor(.accentColor).

标签: swift macos swiftui colors appearance


【解决方案1】:

一种可能的方法是通过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 测试

【讨论】:

    【解决方案2】:

    这是一种可能更灵活的方法,例如,您可以将其用于您的视图模型:

    import Combine
    
    class SomeClass {
        var cancellable: AnyCancellable?
        
        init() {
            cancellable = NSApp.publisher(for: \.effectiveAppearance).sink { appearance in
                print(appearance.name.rawValue)
            }
        }
    }
    

    您可能必须确保调用 cancellable?.cancel() 以便可以取消初始化对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-14
      • 2012-12-13
      • 1970-01-01
      • 1970-01-01
      • 2017-07-26
      • 2011-01-26
      • 1970-01-01
      • 2013-04-26
      相关资源
      最近更新 更多