10

当用户从默认模式切换到暗模式时,我想更改我的状态栏应用程序图标,反之亦然(使用 Swift 3)。这是我到目前为止所拥有的:

func applicationDidFinishLaunching(_ aNotification: Notification) {
    DistributedNotificationCenter.default().addObserver(self, selector: #selector(darkModeChanged(sender:)), name: "AppleInterfaceThemeChangedNotification", object: nil)
}

...

func darkModeChanged(sender: NSNotification) {
    print("mode changed")
}

不幸的是,它不起作用。我究竟做错了什么?

4

4 回答 4

15

我成功地使用了这个 Swift 3 语法:

DistributedNotificationCenter.default.addObserver(self, selector: #selector(interfaceModeChanged(sender:)), name: NSNotification.Name(rawValue: "AppleInterfaceThemeChangedNotification"), object: nil)

func interfaceModeChanged(sender: NSNotification) {
  ...
}
于 2016-10-06T22:56:36.440 回答
1

斯威夫特 5、Xcode 10.2.1、macOS 10.14.4

好东西。我在@Jeffrey 的回答周围的两分钱:

extension Notification.Name {
    static let AppleInterfaceThemeChangedNotification = Notification.Name("AppleInterfaceThemeChangedNotification")
}

所以可以(而不是rawValue):

func listenToInterfaceChangesNotification() {
    DistributedNotificationCenter.default.addObserver(
        self,
        selector: #selector(interfaceModeChanged),
        name: .AppleInterfaceThemeChangedNotification,
        object: nil
    )
}

记住@objc属性:

@objc func interfaceModeChanged() {
    // Do stuff.
}
于 2019-05-11T14:46:53.660 回答
0

如果您只需要更新暗模式的图标图像,您可以通过创建自动更新的动态图像来执行此操作而无需通知。

来自苹果的文档

要创建动态绘制其内容的图像,请使用该init(size:flipped:drawingHandler:)方法使用自定义绘图处理程序块初始化图像。每当系统外观发生变化时,AppKit 都会调用您的处理程序块,让您有机会使用新外观重绘图像。

于 2020-04-14T19:30:22.523 回答
0

所以,我的小补充也是:

enum InterfaceStyle: String {
    case Light
    case Dark
    case Unspecified
}

extension Notification.Name {
    static let AppleInterfaceThemeChangedNotification = Notification.Name("AppleInterfaceThemeChangedNotification")
}

extension NSViewController {
    var interfaceStyle: InterfaceStyle {
        let type = UserDefaults.standard.string(forKey: "AppleInterfaceStyle") ?? "Unspecified"
        return InterfaceStyle(rawValue: type) ?? InterfaceStyle.Unspecified
    }
}

在 NSViewController 中的某处:

        DistributedNotificationCenter.default.addObserver(forName: .AppleInterfaceThemeChangedNotification,
                                                          object: nil, queue: OperationQueue.main) {
            [weak weakSelf = self] (notification) in                // add an observer for a change in interface style
            weakSelf?.setAppearance(toStyle: weakSelf!.interfaceStyle)
        }

wheresetAppearance对风格的变化做出反应。

于 2020-04-17T14:13:41.337 回答