问题
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.
回答1:
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)
+ (void)setSublabelScale:(UIView *)view {
for (id subview in view.subviews) {
if ([subview isKindOfClass:[UILabel class]]) {
[subview setMinimumScaleFactor:0.5];
[subview setAdjustsFontSizeToFitWidth:YES];
} else {
[MYSegmentedControl setSublabelScale:subview];
}
}
}
- (void)layoutSubviews {
[super layoutSubviews];
[MYSegmentedControl setSublabelScale:self];
}
回答2:
I found out that NSAttributedString
has a size
property to it, that will allow me to know how wide the text is for every local. So, I can just do something like:
CGFloat fontSize = 36;
NSAttributedString* attributedString = [[NSAttributedString alloc] initWithString:NSLocalizedString(@"Kilometers", nil).uppercaseString attributes:@{NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue-UltraLight" size:fontSize]}];
if (attributedString.size.width > 200) {
fontSize = 30;
}
来源:https://stackoverflow.com/questions/26453297/scale-uisegmentedcontrol-labels-based-on-width-of-control