How to Change Color of UISwitch in Off State

by

There is no given individual property available to change the color of UISwitch in “off” state. We have the property to change color for “on” state called onTintColor. For "off" sate We can achieve by changing certain combination of properties to UISwitch.

By default background color of UISwitch is clear. We change background color to new color. Remember this changes the background color of UISwitch, and this will result in rectangle solid background color. Our UISwitch must have rounded corners and to match that we update the corner radius of UISwitch. That is it.

Optional step is to update tintColor of UISwitch to match the background color to keep it even.

First way, Inheritence - creating custom UISwitch class. In this example code I am exposing designable property for easy use in our storyboard.


class CustomSwitch: UISwitch{
    @IBInspectable var offTintColor: UIColor? {
        didSet {
            let minSide = min(bounds.size.height, bounds.size.width)
            layer.cornerRadius = minSide / 2
            backgroundColor = offTintColor
            tintColor = offTintColor
        }
    }
}



Second way, Extensions -


extension UISwitch {
    func offTintColor(color: UIColor ) {
        let minSide = min(bounds.size.height, bounds.size.width)
        layer.cornerRadius = minSide / 2
        backgroundColor = color
        tintColor = color
    }
}

You might also like: How to Send Local Video to iMessage in Swift

You might also like: How to Detect Backspace Event in UITextfield and UITextview?

You might also like: How to Get Substring With NSRange in Swift 5

You might also like: Adding two numbers in macOS x86-64 Assembly - Part 2

More Articles

Recommended posts