In my segmented control, sometimes the title is wider than fits its segment. How can I make it truncate?
Let's say the title of segment 1 is Text overlaps
and segment 2 is named ok
.
How I want it to look:
[Text ov...| ok ]
What it looks like:
T[ext overla|ps ok ]
What I tried:
setWidth:forSegment
. Still overlapping, not truncating.UISegmentedControl
Do I have to truncate it myself, before setting the title of the segment?
You have to truncate it yourself.
There is no public API for setting the truncation. Even if you dig through the UISegmentedControl
's private view hierarchy, find the labels, and set lineBreakMode
to UILineBreakModeTailTruncation
, it won't truncate the labels for you. (I tried.)
EDIT: I got this to work. It's not pretty, it might stop working in a future iOS release, and it might get you rejected from the App Store.
static void fixLineBreakMode(UIView *view)
{
if ([view respondsToSelector:@selector(setLineBreakMode:)]) {
[(id)view setLineBreakMode:UILineBreakModeTailTruncation];
[view setFrame:CGRectInset([view.superview bounds], 6, 0)];
} else {
for (UIView *subview in view.subviews)
fixLineBreakMode(subview);
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
fixLineBreakMode(self.segmentedControl);
}