Change width of a segmented control based on titles in each segment?

Viewed 19260

Starts like this, which I like:
Screenshot1.png

But then I add a segment and this happens:
Screenshot2.png The width is set in IB, not in code.

All I need is a method to calculate width on the fly. At the end, it would do something like this:

control.width = (labelWidths + marginWidths);
// where marginWidths = (marginWidth * control.numberOfSegments)
5 Answers

The first option looks like this:

segmentedControl.setWidth(100, forSegmentAt: 0)
segmentedControl.setWidth(50, forSegmentAt: 1)

That gives you individually sized segments while sticking to a value you define, which means you get to tweak the aesthetics as you want. The second option looks like this:

segmentedControl.apportionsSegmentWidthsByContent = true

That hands full control over to iOS, which is probably the best thing to do most of the time.

Available from iOS 5.0

hackingwithswift

It will adjust the size of the segmented control to accommodate the text in the text labels of each segment.

  override func viewDidLoad() {
    super.viewDidLoad()

   UILabel.appearance(whenContainedInInstancesOf: [UISegmentedControl.self]).numberOfLines = 0
   }
Related