Search code examples
iosiphoneswiftuisegmentedcontrol

How to create a custom segment control in Swift


I want to create a segment control that works like in the screenshot. The selected segment should be underlined according to the segment heading text. I have searched for that, but did not find any third party solution. So how can I develop this type of segment control?

Here you can see that the line at the bottom only stretches across the selected segment.

enter image description here


Solution

  • There is an open source project in GitHub named PageMenu. Please have a look, you can even customize the source file CAPSPageMenu.

    https://github.com/PageMenu/PageMenu

    enter image description here

    To update width of the selection hair line, enable the below property.

    menuItemWidthBasedOnTitleTextWidth
    

    Code:

    let parameters: [CAPSPageMenuOption] = [ 
    ... 
    .menuItemWidthBasedOnTitleTextWidth(true),
    ....]
    
    // Initialize scroll menu
    pageMenu = CAPSPageMenu(viewControllers: controllerArray, frame: CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: self.view.frame.height), pageMenuOptions: parameters)
    

    Please try PageMenuDemoStoryboard demo in the project and update parameters as shown in above code.

    enter image description here

    enter image description here