Create UISwitch in Swift Programmatically - Swift 4

A Controller that's offer the binary choice as On/Off. The UISwitch class declare a property and a method to control On/Off state.



This tutorial we are study about declaration of UISwitch, callback and customize the UISwitch.


Define UISwitch:
let switchOnOff = UISwitch(frame:CGRect(x: 150, y: 150, width: 0, height: 0))
switchOnOff.addTarget(self, action: #selector(ViewController.switchStateDidChange(_:)), for: .valueChanged)
switchOnOff.setOn(true, animated: false)
self.view.addSubview(switchOnOff)
State change method: 
@objc func switchStateDidChange(_ sender:UISwitch){
    if (sender.isOn == true){
        print("UISwitch state is now ON")
    }
    else{
        print("UISwitch state is now Off")
    }
}

onTintColor : Set tint color of switch when it is turn on.

tintColor : set tint color of switch when it is turn off.


thumbTintColor : set tint color of the thumb.


onImage: set image of the switch when it is on.
switchOnOff.onImage = UIImage(named: "on-switch")

offImage: set image of the switch when it is off.
switchOnOff.offImage = UIImage(named: "off-switch")

Thanks.
Create UISwitch in Swift Programmatically - Swift 4 Create UISwitch in Swift Programmatically - Swift 4 Reviewed by KIRIT MODI on 07:07:00 Rating: 5

No comments:

Powered by Blogger.