swiftuiswitch

Changing background colour but keeping tint for UISwitch "On" state


Is there any way to change the background color while keeping the grey border when a UISwitch is in the "on" state?

By setting:

switch.onTintColor = myGreen

The switch's border also turns green. But in the off state the background is transparent.

enter image description here


Solution

  • The area that is colored with gray, would be the borderColor of the switch's layer. Thus by doing the following, the border will still be the same no matter the state.

    sender.layer.borderColor = UIColor.gray.cgColor // sender would be the switch if you where to change the color when the switch value has been changed 
    

    By default you can add the gray layer by doing this:

        let switcher = UISwitch()
        switcher.layer.masksToBounds = true
        switcher.layer.borderColor = UIColor.gray.cgColor // <-- we'll add the gray color
        switcher.layer.borderWidth = 2.0 // controll the width or thickness of the border
        switcher.layer.cornerRadius = 15 // from 15 and up you starting getting that round effect 
        switcher.frame = CGRect(x: 50, y: 100, width: 100, height: 40)
        switcher.addTarget(self , action: #selector(didPress), for: .valueChanged)
    

    So now every time the switch is turn on and off you can change the color

    @objc func didPress(sender: UISwitch) {
            switch sender.isOn {
            case true:
                sender.backgroundColor = .green
            case false:
                sender.backgroundColor = .orange
            }
        }