Search code examples
iosobjective-cios9

Is there any way to get the width of the segments in a UISegmentedControl that is proportional to content?


In the case where the segments in a UISegmentedControl are proportional to content widthForSegmentAtIndex seems to return 0 when called from viewDidLayoutSubviews. Is there anyway to get the actual widths? (I am using autolayout.)

If not is there any way to get the subview that corresponds to a segment? segmentedControl.subviews[index] does not work reliably.

If there is no way to do that is there an alternative to UISegmentedControl that can be used?

Thank you!


Solution

  • From my testing it appears that the width of the segments will always be equal, regardless of the size of the text of each individual segment.

    CGFloat segmentWidth = segmentedControl.frame.size.width / segmentedControl.numberOfSegments;

    EDIT

    Unfortunately, the above answer does not work if the segmentedControl is using apportionsSegmentWidthsByContent. I can't find an easy way to get the width of the segment in that case.

    However, you could manually get the text of the segment you're interested in, then calculate how long it 'should' be (depending on how much padding you want on either side), then use that number and use the setWidth:forSegmentAtIndex: method to set the segment to the calculated width, then you would know for sure the width for the segment.