Search code examples
iosswiftuisegmentedcontrol

Custom Segmented Control in Swift for iOS


I'm trying to implement a segmented control but it seems so simple in the layout. I want to customize it:

  • lose the borders for instance
  • have a custom indicator

What would be the way to do it? I know in Android how to customise an TabLayout but here I'm lost to be honest.

enter image description here


Solution

  • I'm quite late to the party, but here's what I'd do:

    Set the background color to .clear

        segmentedControlInstance.backgroundColor = UIColor(red:0.13, green:0.16, blue:0.29, alpha:1.0)
    

    Set the background tint color to .clear

        segmentedControlInstance.tintColor = .clear
    

    I noticed the selected segment's title is bold. Set the text attributes for the two states (.normal & .selected)

        segmentedControlInstance.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.white, NSAttributedStringKey.font: UIFont.systemFont(ofSize: 16)], for: .normal)
        segmentedControlInstance.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.white, NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 16)], for: .selected)
    

    Finally, set the two background images. Caution, I have no idea what to set for the barMetrics parameter:

         segmentedControlInstance.setBackgroundImage(UIImage(name: "selectedSegment", for: .selected, barMetrics: ?)
         segmentedControlInstance.setBackgroundImage(UIImage(name: "normalSegment", for: .normal, barMetrics: ?)
    

    I'll let you play around with the barMetrics parameters.