How to detect switch between macOS default & dark mode using Swift 3

有些话、适合烂在心里 提交于 2019-12-05 07:54:49

I'm using this Swift 3 syntax successfully:

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

func interfaceModeChanged(sender: NSNotification) {
  ...
}

Swift 5, Xcode 10.2.1, macOS 10.14.4

Great stuff. My two cents around @Jeffrey's answer:

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

So one could (instead of rawValue):

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

Remember the @objc attribute:

@objc func interfaceModeChanged() {
    // Do stuff.
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!