Change NSSwitch tint color: Settings > Accessibility > Display > Color Filters

Issue:

I’m trying to change the tint colour of an NSSwitch in the code, but the self.alwaysConnectedSwitch.layer is nil, so the colour is not set.

enter image description here

I’m using the following code:

@IBOutlet weak var alwaysConnectedSwitch: NSSwitch!

override func viewWillAppear() {
    super.viewWillAppear()
    self.alwaysConnectedSwitch.layer?.backgroundColor = CGColor.init(gray: 1, alpha: 1)
}

Answer:

You need to set the wantsLayer property of NSSwitch to true in order to access its layer. Modify your code as follows:

@IBOutlet weak var alwaysConnectedSwitch: NSSwitch!

override func viewWillAppear() {
    super.viewWillAppear()
    self.alwaysConnectedSwitch.wantsLayer = true
    self.alwaysConnectedSwitch.layer?.backgroundColor = CGColor.init(gray: 1, alpha: 1)
}