UISegmentedControl 中的自定义字体禁用 adjustsFontSizeToFitWidth

Custom font in UISegmentedControl disable adjustsFontSizeToFitWidth

我已经为我的 UISegmentedControl 设置了自定义字体,但它似乎禁用了默认的 autoAdjustFontSizeToFitWidth 参数。

之前: 后:

这是我用来设置自定义字体的代码:

UISegmentedControl *segmentedControl = (UISegmentedControl *)subview;
UIFont *font = [UIFont fontWithName:DEFAULT_FONT size:DEFAULT_FONT_SIZE];
NSDictionary *attributes = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
[segmentedControl setTitleTextAttributes:attributes forState:UIControlStateNormal];

有办法保存吗?非常感谢。

编辑: 我想避免

 segmentedControl.apportionsSegmentWidthsByContent = YES;  

如果可能,每个段的宽度始终相同。

我不得不这样做。您可以搜索段控件的子视图并设置属性。

+ (void) setAdjustsFontForWidth:(UIView *) view {
    NSArray * subvies = view.subviews;
    for(UIView * view in subvies) {
        if([view isKindOfClass:[UILabel class]]) {
            UILabel * label = (UILabel *)view;
            NSLog(@"label found: %@", label.text);
            label.adjustsFontSizeToFitWidth = TRUE;
            label.minimumScaleFactor = .1;
        } else {
            [self setAdjustsFontForWidth:view];
        }
    }
}

调用它:

[Utils setAdjustsFontForWidth:mySegmentControl];