As i wrote in my previous post i will try to  write one useful post each day which can be implemented directly in the process of development or can be used as a snippet.

This post is one of the posts i will write as tutorials for beginners.

In this post we will see how UISwitch component can be used in iOS application with Swift.

UISwitch is component from UIKit for displaying and setting Boolean values to variables. With controlling the UISwitch buttons On/Off states we can easily change the variable value to true or false.

In this tutorial we will develop one example where we will show how to use this pretty simple but very useful component.


We are starting with creating the Single View Application in our Xcode IDE.

Screen Shot 2016-07-11 at 11.09.50


Next we are setting Product Name, Organisation Name, Identifier, Language ( Objective-C or Swift ) and Device.

Screen Shot 2016-08-05 at 17.16.17


Your project should look like this after finishing previous step:

Screen Shot 2016-08-05 at 17.20.57


Next we are setting the size of the view and we are choosing compact, portrait for all iPhones.

Screen Shot 2016-08-05 at 19.14.07


We are dropping from the Object Library one UISwitch, UILabel and for manually changing the state of the UISwitch, UIButton.

Screen Shot 2016-08-05 at 19.21.52


We are connecting all components with IBOutlets in the code using Assistant Editor:

Screen Shot 2016-08-05 at 19.25.43

Screen Shot 2016-08-05 at 19.26.15

Screen Shot 2016-08-05 at 19.26.59


Now when all components are connected with corresponding IBOutlets we should have the something like on the image bellow.

Screen Shot 2016-08-05 at 19.32.13


Now we are initializing the label which display active state of the UISwitch component in method override func viewDidLoad().

Screen Shot 2016-08-05 at 19.51.35


Next we are implementing action for manually changing state on our UISwitch control and by touching the button.

Screen Shot 2016-08-05 at 19.43.08

Screen Shot 2016-08-05 at 19.45.00


After making connection in Assistant Editor we have following actions:

Screen Shot 2016-08-05 at 19.45.26

In each action we are writing the simple logic where we check if the state of the switch is on or off.

Screen Shot 2016-08-05 at 20.13.09

When we compile and run the application in the simulator we can try changing the state on switch component or by pressing on the button so we can see if everything we have implemented correctly how its working.

Screen Shot 2016-08-05 at 20.48.01    Screen Shot 2016-08-05 at 20.47.49









Complete source code can be found on my GitHub ready for testing.

Print Friendly, PDF & Email

Leave a Comment

Your email address will not be published. Required fields are marked *