Swift UISwitch color in On state & Off state, Change Switch height in swift - iOS - Swift 4 Tutorials W3Schools

Hot

Post Top Ad

11 Jun 2019

Swift UISwitch color in On state & Off state, Change Switch height in swift - iOS


UISwitch in swift has two states either On or Off. This switches mostly see in native  settings app.

Switch colors change in swift ios


First add switch to view as below, add following code in viewDidLoad() method:

let switchButton = UISwitch()
switchButton.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(switchButton)
switchButton.centerXAnchor.constraint(equalTo: self.view.centerXAnchor, constant: 0).isActive = true
switchButton.centerYAnchor.constraint(equalTo: self.view.centerYAnchor, constant: 0).isActive = true
switchButton.isOn = true

Run the code, you will see switch in On state with green color.

Tap on switch to turn off, color changes to white.

Green is for On, White is for Off these are default colors for switch in swift.

Now we will change default colors,

On - Blue 
Off - Red 

Add the following to the end of viewDidLoad() method:


// Colors
switchButton.onTintColor = UIColor.blue
switchButton.tintColor = UIColor.red
switchButton.thumbTintColor = UIColor.white
switchButton.backgroundColor = UIColor.red
switchButton.layer.cornerRadius = 16

Run the code you will see different colors unlike default color for switch in ios.

Change Switch Height:  

For changing the height of switch in swift we need to do following,  Add below code to the end of viewDidLoad():

// change height
switchButton.transform = CGAffineTransform(scaleX: 0.6, y: 0.6)

Run code, we will switch button size with small size.






No comments:

Post a Comment

Post Top Ad