How to use Segmented Control


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

1. 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.

new project X code


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

iPhone 4 inch


3. Add segmented control to the storyboard

segmented control


4. Set its width to 300

set width to 300


5. Make segment Value to 3

create 3 segments


6. Add following names to storyboard

set segment names


7. Add label & set its width to 300. Make label alignment Center

add label


8. Connect segmented control to swift file as outlet

segment as outlet


9. Connect label to swift file as outlet

label as outlet


10. Connect segmented control to swift file as action

segment as action


11. Add following code to view did load. When app is opened then by default segment 0 is selected.

    override func viewDidLoad() {
        // 11
        segment.selectedSegmentIndex = 0
        content.text = "New segment feature is included"
        // Do any additional setup after loading the view, typically from a nib.

12. Add following code to index change button

    @IBAction func indexChanged(sender: UISegmentedControl) {
        // 12
        switch segment.selectedSegmentIndex {
        case 0:
            content.text = "New segment feature is included"
        case 1:
            content.text = "We make iPhone apps"
        case 2:
            content.text = ""

Switch case is short hand for multiple if else loops. See complete list of swift short hands here.
Now build and run app in iPhone 5s And click on different segment to test it

Screen Shot 2015-03-05 at 5.34.34 pm
Download X code file
Your challenge is to use segmented control as picker.
Uber challenge is to save picked value using NSUserdefaults

Screen Shot 2015-03-05 at 5.36.45 pm
Download Challenge Solution

Total 3 Votes

Tell us how can I improve this tutorial?

+ = Verify Human or Spambot ?