How can I calculate correct widths for UISegmentedControl segments?

progrmr picture progrmr · Jul 14, 2011 · Viewed 13.7k times · Source

I'm trying to use a UISegmentedControl but having trouble calculating the width of the segments. The control makes the segments all the same width which doesn't work for some titles, like this one:

http://morrisphotoart.com/tmp/Screenshot2011-07-13_21.17.33.png

I can write code to calculate the segment width if I knew which font and call the setWidth:forSegmentAtIndex: method but how can I get the font? Or is there another way?

The left and middle segment's titles are not fixed so I can't hardcode the widths.

Answer

Camsoft picture Camsoft · Mar 6, 2013

If you can support iOS 5 and later then you can use the property apportionsSegmentWidthsByContent and set it to YES.

From the iOS 5 docs:

apportionsSegmentWidthsByContent

Indicates whether the control attempts to adjust segment widths based on their content widths.

@property(nonatomic) BOOL apportionsSegmentWidthsByContent

Discussion

If the value of this property is YES, for segments whose width value is 0, the control attempts to adjust segment widths based on their content widths.