这似乎没什么好事,但我找不到任何方法来做到这一点。基本上我所拥有的是UISegmentedControl
,其中包含两个使用NSLocalizedString
的本地化标签。我设置了字体大小,一切看起来都很棒,有英语和其他一些语言。但是,在日语和其他语言中,字符较大并导致标签被截断。
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];
有没有办法根据标签宽度缩放标签的字体大小?我意识到这些不是正常的UILabel
,所以没有adjustsFontSizeToFitWidth
属性。
答案 0 :(得分:1)
我正在处理同样的问题。这是我的解决方案(边缘有点粗糙):
我将分段控件子类化,然后在我的子类中,执行以下操作。希望这可以帮助! (在iOS 7和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];
}
答案 1 :(得分:0)
我发现NSAttributedString
有一个size
属性,这样我就可以知道每个本地文本的宽度。所以,我可以做类似的事情:
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;
}