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.
Next we are setting Product Name, Organisation Name, Identifier, Language ( Objective-C or Swift ) and Device.
Your project should look like this after finishing previous step:
Next we are setting the size of the view and we are choosing compact, portrait for all iPhones.
We are dropping from the Object Library one UISwitch, UILabel and for manually changing the state of the UISwitch, UIButton.
We are connecting all components with IBOutlets in the code using Assistant Editor:
Now when all components are connected with corresponding IBOutlets we should have the something like on the image bellow.
Now we are initializing the label which display active state of the UISwitch component in method override func viewDidLoad().
Next we are implementing action for manually changing state on our UISwitch control and by touching the button.
After making connection in Assistant Editor we have following actions:
In each action we are writing the simple logic where we check if the state of the switch is on or off.
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.
Complete source code can be found on my GitHub ready for testing.