Tuesday, May 24, 2016

Create a UISwitch programmatically

Update: July 8, 2017 (Swift 3.1 + Xcode 8.3.3)
Original Post: May 24, 2016 (Swift 2.2 + Xcode 7.3.1)

The code below shows how to create a UISwitch programmatically with various colors.

Modify ViewController.swift as:

Update: July 8, 2017 (Swift 3.1 + Xcode 8.3.3)


import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let mySwitch = UISwitch()
        mySwitch.center = view.center
        mySwitch.setOn(false, animated: false)
        mySwitch.tintColor = UIColor.blue
        mySwitch.onTintColor = UIColor.cyan
        mySwitch.thumbTintColor = UIColor.red
        mySwitch.backgroundColor = UIColor.yellow
        mySwitch.addTarget(self, action: #selector(switchChanged(sender:)), for: UIControlEvents.valueChanged)
        view.addSubview(mySwitch)
    }
    
    func switchChanged(sender: UISwitch!) {
        print("Switch value is \(sender.isOn)")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

Original Post: May 24, 2016 (Swift 2.2 + Xcode 7.3.1)

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let mySwitch = UISwitch()
        mySwitch.center = view.center
        mySwitch.setOn(false, animated: false)
        mySwitch.tintColor = UIColor.blueColor()
        mySwitch.onTintColor = UIColor.cyanColor()
        mySwitch.thumbTintColor = UIColor.redColor()
        mySwitch.backgroundColor = UIColor.yellowColor()
        mySwitch.addTarget(self, action: #selector(switchChanged(_:)), forControlEvents: UIControlEvents.ValueChanged)
        view.addSubview(mySwitch)
    }
    
    func switchChanged(sender: UISwitch!) {
        print("Switch value is \(sender.on)")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

Result:



No comments:

Post a Comment