Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force a view controller to use light or dark mode in macOS?

Tags:

macos

swift

I know there is a way to programmatically override the interface style in iOS like below:

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        overrideUserInterfaceStyle = .dark    
    }
}

Howover, I tried searching for something similar in macOS but not able to find one. Is there a way to achieve this in macOS?

like image 898
Ram Patra Avatar asked Oct 15 '22 04:10

Ram Patra


2 Answers

It can be done via

public protocol NSAppearanceCustomization : NSObjectProtocol {
    @available(OSX 10.9, *)
    var appearance: NSAppearance? { get set }

The NSApplication, NSWindow, and NSView conform to this protocol, so you can use it like

window.appearance = NSAppearance(named: .aqua)
window.makeKeyAndOrderFront(nil)
like image 183
Asperi Avatar answered Dec 27 '22 12:12

Asperi


I found it finally. You can do the same in macOS like below:

class ViewController: NSViewController { 

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do view setup here.
        view.appearance = NSAppearance(named: .darkAqua)

    }

}
like image 37
Ram Patra Avatar answered Dec 27 '22 12:12

Ram Patra