iOS Tutorials: Introduction to Segmented Control

OVERVIEW

This project introduce the use of Segmental Control by implementing several color code in which once selected will portray the color selected.

We will first design the UI by using the Segmental Control and View from the Object Library and change the background color of View to any visible color beside white or else you won’t know where the View is.

Then, click on the Segmental Control and change some of it’s settings such as adding one more segmental control and rename it’s content. 

Then, create an IBOutlet for both objects and an IBAction for Segmental Control. In the IBAction, write a switch statement that will detect the selected segmental and project the color on the View. Your code should look like below:

class ViewController: UIViewController {

    @IBOutlet weak var segmentControl: UISegmentedControl!
    @IBOutlet weak var colorStatus: UIView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func selectColor(_ sender: Any) {
        switch segmentControl.selectedSegmentIndex {
        case 0:
            colorStatus.backgroundColor = UIColor.red
        case 1:
            colorStatus.backgroundColor = UIColor.green
        case 2:
            colorStatus.backgroundColor = UIColor.blue
        default:
            colorStatus.backgroundColor = UIColor.lightGray
        }
    }
}

The result would look like below:

 

The code is uploaded on GitHub

  • Article By :
    Founder of DaddyCoding. Studied Computer Science, Information System and Information Technology at BYU-Hawaii. Currently spending most of my time researching and learning on helping to expose making iOS apps.

Random Posts

Leave a Reply

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

*
*