How to use UISwitch to save settings


This tutorial has been updated for X code 7.3 & swift 2.2

First lets set up the x code project as usual. Create new single view application X code project. Set the values as follows and save it on your desktop.

Screen Shot 2015-03-06 at 7.27.41 pm

Go to main storyboard and select view controller. Set its size iPhone 4-inch in attribute section.

Screen Shot 2015-03-05 at 9.45.20 pm

Add label & switch to the main storyboard

Screen Shot 2015-03-06 at 7.30.22 pm

Change labels text to ”White Background”

Screen Shot 2015-03-06 at 7.43.57 pm


Connect switch as outlet to swift file

Screen Shot 2015-03-06 at 7.33.50 pm

Connect switch as action to swift file

Screen Shot 2015-03-06 at 7.34.42 pm

Add following code in view did load. This will set initial value for switch

override func viewDidLoad() {

    mySwitch.on = false
    self.view.backgroundColor = UIColor.lightGrayColor()

    // Do any additional setup after loading the view, typically from a nib.

Add following code in switch changed button

@IBAction func switchChanged(sender: UISwitch) {

    if sender.on {
        self.view.backgroundColor = UIColor.whiteColor()
    else {
        self.view.backgroundColor = UIColor.lightGrayColor()


Now build and run the app in iPhone 5s. Turn on the switch & turn off the switch.

Screen Shot 2015-03-06 at 7.43.41 pm
Download X code file

Challenge Save switch state with NSUserdefaults

(Hint: save the bool value with NSUserdefaults)

Uber Challenge Save background color with NSUserdefaults

(Hint: Use NSKeyedArchiver)

Download Challenge Solution
Total 0 Votes

Tell us how can I improve this tutorial?

+ = Verify Human or Spambot ?