In this post we will create simple project for demonstrating how to use UISegmentedControl component within your application but also we will use other components like UITextField, UILabel and UIButton which will make our simple project much more rich.
UISegmentedControl is very simple UI component with two segments by default used for changing the state of some component in application or setting some properties. Number of segments is variable, which mean we can set more then two segments.
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 UISegmentedControl, three UILabel components, two UITextField components and one UIButton for testing the state of the UISegmentedControl.
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.
Next we are implementing actions, first which is executed after manually changing the segment on our UISegmentedControl control and second for testing the active segment by touching the button.
After making connection in Assistant Editor we have following actions:
In each action we are writing the simple logic for demonstration.
First method which is executed by touching the button we are checking which segment is selected and depending on selected segment we are taking typed value from correct UITextField component and we are setting as text value at the label.
Second method is executed by changing the state on UISegmentedControl component so we are setting the text depending on which segment is selected.
When we compile and run the application in the simulator we can try changing the state on segmented 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.