Brief About UISegmentedControl In Swift 3

Posted By : Gunjan Gumber | 26-Sep-2017

I have seen most of developers are figuring out to switch multiple view on same view controller and the simple solution for that is UISEGMENTED CONTROL 

UISegmentedControl has a strip in which each Strip acts like a button. If we want to group many buttons together we should go for segmentedControl as it gives us clean and usuable appearence.
Each segmented control looks like a radio button. Each Segment can display different text Value on a label
A segmented control can display a title (an NSString object) or an image (UIImage object).  
To fit proportionally within their superview,UISegmentedControl object automatically resizes segments.

 

**Increase Height for  UISegmentedControl

To Use Segment control , we simply drag an drop segmented control in storyboard and to increase its height(as we cannot increase height from Storyboard), we can define a Outlet of height  in the view controller Type NSConstraint and directly give its height as we want from view controller

and if we want to insert segment programatically then:-

let segmentedControl = UISegmentedControl()
segmentedControl.insertSegment(withTitle: "Title", at: 0, animated: true)
segmentedControl.setTitle("Title", forSegmentAt: 0)

To register target action for segmented control:-

segmentedControl.addTarget(self, action: "action:", forControlEvents: .ValueChanged)
 

 

To get the index of segment , we use :-

segmentedControl.selectedSegmentIndex
 

example:-

 func indexChanged(_ sender: AnyObject) {
    
    if (segmentedControl.selectedSegmentIndex == 0)
       {
       //write your code
       }
    else if (segmentedControl.selectedSegmentIndex == 1)
       {
       //write your code
       }
}

 

Multiple segmented control on same view 

 @IBOutlet weak var segmentedControl1: UISegmentedControl!
@IBOutlet weak var segmentedControl2: UISegmentedControl!

//MARK: CLick event of segment controlz

func onClickSegment(sender: UISegmentedControl) 
{
    print(sender.selectedSegmentIndex)
    if segmentedControl1.selectedSegmentIndex == 0 && segmentedControl2.selectedSegmentIndex == 1
    {
        //write your code
    }
}

About Author

Author Image
Gunjan Gumber

Gunjan is a bright IOS developer with good knowledge in Swift ,Json, quite good at building user interface.

Request for Proposal

Name is required

Comment is required

Sending message..