How To Use iOS UISegmentedControl In Swift Programmatically Example

This example will tell you how to add and use the iOS UISegmentedControl object both in the Main.storyboard visually and programmatically in swift source code. There are two UISegmentedControl objects on the app screen. The above one is added to the Main.storyboard visually, when click it’s item, it will display the item title or image in the above label. The bottom one is added in swift source code, when click it’s item, it will prompt an alert dialog to display the selected item title text. Below is the example video.

If you can not watch the above video, you can see it on URL https://youtu.be/5BgD5l-B8cQ.

1. How To Add UISegmentedControl Component Visually In Main.storyboard Steps.

  1. Create an Xcode project using the Single View App template.
  2. Click the Main.storyboard file in the project files list to edit it.
  3. Click Xcode View —> Show Library menu item to open the UI component object library window.
  4. Input keyword seg in the library window search box, and drag and drop the SegmentedControl to the Main.storyboard screen.
  5. You can set the segment item numbers, each segment’s title or image by click View —> Inspectors —> Show Attributes Inspector menu item at Xcode top menu bar.
  6. Select the first segment control object, then click the Align icon (auto layout constraints align) at the main storyboard bottom right to add a constraint to make it center layout in the horizontal direction by checking the Horizontally in Container checkbox.
  7. Also, add a label into the Main.storyboard screen by drag and drop it from UI component library. And add one constraint ( Label.top = Safe Area.top + 100 ) to the label to make it 100 pt away from the iPhone’s top safe area. Add two constraints to the segment control to make it 100 pt away from the label top ( Segment1.top = Label.top + 100 ), and layout it in screen horizontal center ( Segment1.centerX = centerX ). You can see the three constraints under the View Controller Scene —> View Controller —> View —> Constraints item. You can refer article How To Add Constraints In Xcode 10 To Implement Auto Layout, iOS Auto Layout With Constraint Example to learn how to do it.
  8. You should add @IBOutlet variables to the label and segment control,  and add the @IBAction function to process the segment control value changed event. You can learn this from the article How To Connect Storyboard UI Component To ViewController Class Code.

2. How To Add iOS Segmented Control Component Programmatically Steps.

  1. Click to edit the ViewController.swift file.
  2. Then copy the below code into it. The code contains how to create the second segmented control, how to add both text and image items into it, how to add layout constraints to it, how to process it’s value changed events etc. It also contains how to layout the label at the screen horizontal center by add constraints to it.
    //
    //  ViewController.swift
    //  iOSUISegmentedControlExample
    //
    //
    
    import UIKit
    
    class ViewController: UIViewController {
    
        // This @IBOutlet variable refer to the label component.
        @IBOutlet weak var label: UILabel!
        // This @IBOutlet variable refer to the segment control component.
        @IBOutlet weak var segment1: UISegmentedControl!
        
        // This segment control component is created programmatically in source code.
        var segment2: UISegmentedControl = UISegmentedControl()
        
        // This function will be invoked when the app main view is loaded.
        override func viewDidLoad() {
            super.viewDidLoad()
            
            centerLayoutLabel()
    
            addSecondUISegmentedControl()
            
        }
        
        /* This functin will layout the label at the screen center in horizontal direction.*/
        func centerLayoutLabel(){
            // Initialize a NSLayoutConstraint object, and make it layout at the center of the screen horizontal direction.
            let centerConstraint = NSLayoutConstraint.init(item: label, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.view, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1.0, constant: 0)
            // Active center constraint.
            centerConstraint.isActive = true
            
            //let centerXAnchor = label.centerXAnchor.constraint(equalTo: self.view.centerXAnchor)
            //centerXAnchor.isActive = true
        }
        
        /* This function will add the second UISegmentedControl object programmatically. It will also layout it at screen horizontal center.
           It will be placed 100 px away from the first UISegmentedControl object which is added in Main.storyboard.
         */
        
        func addSecondUISegmentedControl(){
            
            // First create the initial segments title array.
            let segments = ["Left", "Right"]
            
            // Create the second UISegmentedControl object.
            segment2 = UISegmentedControl(items: segments)
            
            // Insert another segment title in the UISegmentedControl object.
            segment2.insertSegment(withTitle: "Hello", at: 2, animated: true)
            
            // Create a UIImage object with resource name added in the Assets.xcassets folder.
            let image = UIImage(named: "AppImage")
            // Insert above UIImage object in the UISegmentedControl object.
            segment2.insertSegment(with: image, at: 3, animated: true)
            
            // Get segment1's x, y, width and height value.
            let segment1X = segment1.frame.origin.x
            let segment1Y = segment1.frame.origin.y
            let segment1Width = segment1.frame.width
            let segment1Height = segment1.frame.height
            
            // Create the CGRect object for the second UISegmentedControl object.
            let segment2Rect = CGRect(x: segment1X, y: segment1Y + 100, width: segment1Width, height: segment1Height)
            // Set the second UISegmentedControl's frame with above CGRect object.
            segment2.frame = segment2Rect
            
            // Register the value changed event to the pressSegmentTwo function for the second UISegmentedControl object.
            segment2.addTarget(self, action: #selector(pressSegmentTwo), for: UIControl.Event.valueChanged)
            
            // Add the second UISegmentedControl object to the app main view.
            self.view.addSubview(segment2)
            
        }
    
        /* This function will be called when user press the frist UISegmentedControl object. */
        @IBAction func pressSegmentOne(_ sender: UISegmentedControl) {
            
            // Get user selected UISegmentedControl item index.
            let selIdx:Int = sender.selectedSegmentIndex
            
            // Get selected item title or image.
            let selSegTitle: String! = sender.titleForSegment(at: selIdx)
            let selSegImage: UIImage! = sender.imageForSegment(at: selIdx)
            
            // If selected item's title is not nil then set it's value to the label object.
            if(selSegTitle != nil){
                label.text = selSegTitle
            }
            
            // If selected item's image is not nil then set the image as the label object's background image.
            if(selSegImage != nil){
                let attachment = NSTextAttachment()
                
                attachment.image = selSegImage
                
                let attachmentString = NSAttributedString(attachment: attachment)
                
                if(selSegTitle != nil){
                    let myString = NSMutableAttributedString(string: selSegTitle)
                
                    myString.append(attachmentString)
                
                    label.attributedText = myString
                }else
                {
                    label.attributedText = attachmentString
                }
            
            }
            
        }
        
        /* This function will be invoked when user select different value in the second UISegmentedControl object. */
        @objc func pressSegmentTwo(_ sender: UISegmentedControl){
            
            // Get user selected segment index, title and image.
            let selIdx:Int = sender.selectedSegmentIndex
            var selSegTitle: String! = sender.titleForSegment(at: selIdx)
            let selSegImage: UIImage! = sender.imageForSegment(at: selIdx)
            
            // If user select image then show message "You select one image." in the prompt alert dialog.
            if(selSegImage != nil){
                selSegTitle = "You select one image."
            }
                           
            // Create the alert dialog with segment title as alert dialog message.
            let alertController:UIAlertController = UIAlertController(title: "You select", message: selSegTitle, preferredStyle: UIAlertController.Style.alert)
            
            // Crteate alert dialog action button.
            let alertAction:UIAlertAction = UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler:nil)
            
            // Add the alert action button to the prompt dialog.
            alertController.addAction(alertAction)
            
            // Present the alert dialog.
            present(alertController, animated: true, completion: nil)
        }
        
    }
  3. Because we add an image in the second segmented control item, so we should add an image in the project Assets.xcassets folder like below. You can read the article How To Add iOS App Icon, Image, Color Set To Xcode Project Assets Catalog Correctly to learn more.

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.