Reputation: 1094
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!
Upvotes: 1
Views: 2301
Reputation: 712
The following category gives NSSegmentedControl the ability to tell you its computed segment widths. It's not perfect- see the disclaimer in comments.
@implementation NSSegmentedControl (SegmentedControlWidthComputation)
/* Note: This implementation doesn't properly handle cells with images. It also makes some guesses about AppKit's behavior, and should be treated as an estimation rather than an exact value. */
- (CGFloat)computedWidthForSegment:(NSInteger)SEGIDX
{
CGFloat pad = 0;
switch (self.controlSize) {
case (NSControlSizeMini): pad = 16; break;
case (NSControlSizeSmall): pad = 22; break;
case (NSControlSizeRegular): pad = 28; break;
}
return [[NSAttributedString alloc] initWithString:[self labelForSegment:SEGIDX] attributes:@{NSFontAttributeName:self.font}].size.width + pad;
}
@end
Upvotes: 0
Reputation: 3981
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.
Upvotes: 2