1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swift:macOSでテーマの切り替えを検出する

Last updated at Posted at 2018-12-08

はじめに

macOS MojaveになってからDark Modeが話題になっていますが,アプリを作る側としては,こちらへの対応で忙しいですね.
さて,ライトモードとダークモードのテーマ切り替えを検出する方法を見つけましたのでまとめておきます.
※Mojave以降のmacOSでないと動かないことに気づきました.

ソース(Mojave以降,表示中のView向け)

NSViewのサブクラス
class customView: NSView {

    private var currentAppearance: NSAppearance.Name!

    required init?(coder decoder: NSCoder) {
        super.init(coder: decoder)
        currentAppearance = self.effectiveAppearance.name
    }
    
    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        currentAppearance = self.effectiveAppearance.name
    }

    override func viewDidChangeEffectiveAppearance() {
        if currentAppearance != self.effectiveAppearance.name {
            currentAppearance = self.effectiveAppearance.name
            //外観モードが切り替わった時の処理
        }
    }

}

ソース(万能)

let center = DistributedNotificationCenter.default()
let userDefaults = UserDefaults.standard

override func viewDidLoad() {
    let name = "AppleInterfaceThemeChangedNotification"
    center.addObserver(self, selector: #selector(self.refreshDarkMode(_:)),
                       name: NSNotification.Name(rawValue: name), object: nil)
}

@objc func refreshDarkMode(_ sender: NSNotification) {
    let currentStyle = userDefaults.string(forKey: "AppleInterfaceStyle") ?? "Light"
    Swift.print(currentStyle)
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?