[英]How to detect switch between macOS default & dark mode using Swift 3
我想在用戶從默認模式切換到暗模式時更改我的狀態欄應用程序圖標,反之亦然(使用 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")
}
不幸的是,它不起作用。 我做錯了什么?
我成功地使用了這個 Swift 3 語法:
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
很棒的東西。 我對@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.
}
如果您只需要為暗模式更新圖標圖像,您可以通過創建自動更新的動態圖像來完成此操作而無需通知。
來自蘋果的文檔:
要創建動態繪制其內容的圖像,請使用
init(size:flipped:drawingHandler:)
方法使用自定義繪圖處理程序塊初始化您的圖像。 每當系統外觀發生變化時,AppKit 都會調用您的處理程序塊,讓您有機會使用新外觀重新繪制圖像。
所以,我的小補充:
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)
}
其中setAppearance
對樣式的變化做出反應。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.