Super Easy! Switch Tab Using UISegmented Control in Swift 5

 
Maniisha Gorasiya

In this tutorial we create 2 segment tabs inside a UISegmentedControl. Each segment tab will display a different text value on a label.
Default design of UISegmented control is simple and can not changeable from StoryBoard. For show your segment tab more attractive, here i will write some easy and simple code with animation. This code is totally convert default UISegment into awesome tab looks like material designed tab.

Here, i will create beautiful designed with amazing animation using less and simple code. You can implement this super easy tab code where you want. In this tutorial i will create class for designed segment tabs, it can be implement at every where also in StoryBoard of your project.

First of all, drag & drop UISegmented Control in Storyboard from Objects list.




Now, create a class for custom segment control.


class SegmentedControl: UISegmentedControl{    

}

 

Create Extension for shape and fill color of custom UISegmented control

 


extension UIImage{

    class func getSegRect(color: CGColor, andSize size: CGSize) -> UIImage{

        UIGraphicsBeginImageContextWithOptions(size, false, 0.0)

        let context = UIGraphicsGetCurrentContext()

        context?.setFillColor(color)

        let rectangle = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height)

        context?.fill(rectangle)

        

        let rectangleImage = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()

        return rectangleImage!

    }

}



We’ll use this extension in the segment extension, ?

Here UISegmentedControl Extension for remove the bottom underline of the segment tab with animation

   


extension UISegmentedControl{

    func removeBorder(){

        let background = UIImage.getSegRect(color: UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1.0).cgColor, andSize: self.bounds.size) // segment background color and size

        self.setBackgroundImage(background, for: .normal, barMetrics: .default)

        self.setBackgroundImage(background, for: .selected, barMetrics: .default)

        self.setBackgroundImage(background, for: .highlighted, barMetrics: .default)


        let deviderLine = UIImage.getSegRect(color: UIColor.black.cgColor, andSize: CGSize(width: 1.0, height: 5))

        self.setDividerImage(deviderLine, forLeftSegmentState: .selected, rightSegmentState: .normal, barMetrics: .default)

        self.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.gray], for: .normal)

        self.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor(red: 61/255, green: 192/255, blue: 200/255, alpha: 1.0)], for: .selected)

    }




Than create highlightSelectedSegment() function for highlight the selected tab at same extension of UISegmentControl,


 

 

func highlightSelectedSegment(){
        removeBorder()
        let lineWidth: CGFloat = self.bounds.size.width / CGFloat(self.numberOfSegments)
        let lineHeight: CGFloat = 7.0
        let lineXPosition = CGFloat(selectedSegmentIndex * Int(lineWidth))
        let lineYPosition = self.bounds.size.height - 6.0
        let underlineFrame = CGRect(x: lineXPosition, y: lineYPosition, width: lineWidth, height: lineHeight)
        let underLine = UIView(frame: underlineFrame)
        underLine.backgroundColor = UIColor(red: 61/255, green: 192/255, blue: 200/255, alpha: 1.0). // bottom line color
        underLine.tag = 1
        self.addSubview(underLine)
    }

 


And the last function for change the position of that bottom line of selected tab and the Spring Animation,

Again add this function in extension of UISegmentControl. Later we’ll use at the value change action of UISegmented Control.

 

 

func underlinePosition(){
        guard let underLine = self.viewWithTag(1) else {return}
        let xPosition = (self.bounds.width / CGFloat(self.numberOfSegments)) * CGFloat(selectedSegmentIndex)
        UIView.animate(withDuration: 0.5, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.8, options: .curveEaseInOut, animations: {
            underLine.frame.origin.x = xPosition
        })
    }
} // End of the UISegmentControl Extension

 

 



Now come to the ViewController file and declare the UISegment Control using SegmentedControl Class and connect it with Storyboard:

 

 

@IBOutlet var segmentedControl: SegmentedControl!

 

 

Add some custom design for segment tab in

func viewDidLoad(),

 


segmentedControl.frame = CGRect(x: self.segmentedControl.frame.minX, y: self.segmentedControl.frame.minY, width: segmentedControl.frame.width, height: 60)

segmentedControl.highlightSelectedSegment() 




than add the

segmentedControl.underlinePosition

function in value change action of UISegment control,

 


@IBAction func segmentedControlDidChange(_ sender: UISegmentedControl){

        segmentedControl.underlinePosition()

}



That’s it your custom tab is ready here with beautiful spring animation !

Here you can watch video tutorial: https://www.youtube.com/watch?v=WmK02eLrSvQ





Comments

No Comment

Leave a Comment

Your email address will not be published.



#212, Time Square Empire,SH 42 Mirjapar highway,Bhuj Kutch 370001
+(91) 97 26 134340
Mon-Fri 9:00am-6:00pm
talk@lpktechnosoft.com
24 X 7 online support