Custom font in UISegmentedControl disable adjustsFontSizeToFitWidth

匆匆过客 提交于 2019-12-14 01:21:49

问题


I have set a custom font for my UISegmentedControl, but it seems to disable the default autoAdjustFontSizeToFitWidth parameter.

Before: After:

Here is the code I apply to set my custom font:

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];

Is there a way to preserve it? Many thanks.

EDIT: I would like to avoid

 segmentedControl.apportionsSegmentWidthsByContent = YES;  

if possible to always have same width for every segment.


回答1:


I just had to do this. You can search through the subviews of the segment control and set the properties.

+ (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];
        }
    }
}

Call it with:

[Utils setAdjustsFontForWidth:mySegmentControl];


来源:https://stackoverflow.com/questions/32155530/custom-font-in-uisegmentedcontrol-disable-adjustsfontsizetofitwidth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!