The method in prgrmr answer here works perfectly for its intended purpose, but it is not.
Instead of adding extra overhead using custom UILabel routines,
I changed the example code in the link above to come up with the following:
- (void)resizeSegmentsToFitTitles:(UISegmentedControl *)control {
CGFloat textWidth = 0;
CGFloat marginWidth = 0;
NSUInteger nSegments = control.subviews.count;
UIView *aSegment = [control.subviews objectAtIndex:0];
UIFont *theFont = nil;
for (UILabel *label in aSegment.subviews) {
if ([label isKindOfClass:[UILabel class]]) {
theFont = label.font;
break;
}
}
for (NSUInteger i = 0; i < nSegments; i++) {
NSString *title = [control titleForSegmentAtIndex:i];
CGFloat width = [title sizeWithFont:theFont].width;
CGFloat margin = 15;
if (width > 200) {
NSString *ellipsis = @"…";
CGFloat width2 = [ellipsis sizeWithFont:theFont].width;
while (width > 200-width2) {
title = [title substringToIndex:title.length-1];
width = [title sizeWithFont:theFont].width;
}
title = [title stringByAppendingString:ellipsis];
}
[control setTitle:title forSegmentAtIndex:i];
textWidth += width;
marginWidth += margin;
}
for (NSUInteger i = 0; i < nSegments; i++) {
CGFloat textWidth = [[control titleForSegmentAtIndex:i]
sizeWithFont:theFont].width;
CGFloat segWidth = roundf(textWidth + (marginWidth / nSegments));
[control setWidth:segWidth forSegmentAtIndex:i];
}
[control setFrame:CGRectMake(0, 0, (textWidth + marginWidth), 30)];
}