4

這看起來似乎毫無道理,但我找不到任何方法來做到這一點。基本上我有一個UISegmentedControl與兩個本地化標籤使用NSLocalizedString。我已經設置了字體大小,並且英文和其他幾種語言的內容都很棒。但是,在日文和其他語言中,字符較大並導致標籤被截斷。基於控件寬度的比例UISegmentedControl標籤

enter image description here

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

我發現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; 
} 
1

我正在處理相同的問題。這是我的解決方案(有點粗糙的邊緣):

我subclass分段的控制,然後在我的子類,執行以下操作。希望這可以幫助! (在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]; 
}