简体   繁体   中英

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.

在此输入图像描述

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.

If what I need to customize wasn't on this list, UISegmentedControl Docs , I'd build my own.

In your image, I'd use two buttons, a view for the indicator, and some logic to respond to user interactions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM