This seems like a no brainer, but I cannot find any way to do this. Basically what I have is a UISegmentedControl
with two localized labels using NSLocalizedString
. I have set the font size and everything looks great in English and a few other languages. But, in Japanese and other languages the characters are larger and cause the label to be truncated.
self.segmentedControl = [[UISegmentedControl alloc] initWithItems:
[NSArray arrayWithObjects:
NSLocalizedString(@"Miles", nil).uppercaseString,
NSLocalizedString(@"Kilometers", nil).uppercaseString,
nil]];
self.segmentedControl.apportionsSegmentWidthsByContent = YES;
self.segmentedControl.selectedSegmentIndex = self.metric ? 1 : 0;
[self.segmentedControl addTarget:self action:@selector(changeMetric:) forControlEvents:UIControlEventValueChanged];
self.segmentedControl.frame = CGRectMake(8, middleHolder.frame.size.height/2+60, progressWidth, 30);
self.segmentedControl.center = CGPointMake(self.view.center.x, self.segmentedControl.center.y);
[self.segmentedControl setTitleTextAttributes:@{
NSForegroundColorAttributeName: [UIColor whiteColor],
NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue-UltraLight" size:36]
} forState:UIControlStateSelected];
[self.segmentedControl setTitleTextAttributes:@{
NSForegroundColorAttributeName: [[UIColor whiteColor] colorWithAlphaComponent:0.3],
NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue-UltraLight" size:36]
} forState:UIControlStateNormal];
self.segmentedControl.tintColor = [UIColor clearColor];
self.segmentedControl.autoresizingMask = UIViewAutoresizingFlexibleWidth;
[middleHolder addSubview:self.segmentedControl];
Is there any way to scale the font size of the label depending on the label width? I realize that these are not normal UILabel
's, so there is no adjustsFontSizeToFitWidth
property.
I found out that
NSAttributedString
has asize
property to it, that will allow me to know how wide the text is for every local. So, I can just do something like:I'm tackling with the same issue. Here is my solution (a bit rough around the edges):
I subclass the segmented control and then in my subclass, do the following. Hope this helps! (Tested on iOS 7 and 8)