How to figure out the font size of a UILabel when -adjustsFontSizeToFitWidth is set to YES?

后端 未结 5 2131
醉话见心
醉话见心 2020-11-30 05:33

When myLabel.adjustsFontSizeToFitWidth = YES, UILabel will adjust the font size automatically in case the text is too long for the label. For example, if my lab

5条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 06:31

    UILabel *txtLabel = [[UILabel alloc] initWithFrame:rectMax];
    txtLabel.numberOfLines = 1;
    txtLabel.font = self.fontMax;
    txtLabel.adjustsFontSizeToFitWidth = YES;
    txtLabel.minimumScaleFactor = 0.1;
    [txtLabel setText:strMax];
    
    UILabel *fullSizeLabel = [UILabel new];
    fullSizeLabel.font = txtLabel.font;
    fullSizeLabel.text = txtLabel.text;
    fullSizeLabel.numberOfLines = 1;
    [fullSizeLabel sizeToFit];
    
    CGFloat actualFontSize = txtLabel.font.pointSize * (txtLabel.bounds.size.width / fullSizeLabel.bounds.size.width);
    actualFontSize = actualFontSize < txtLabel.font.pointSize ? actualFontSize : txtLabel.font.pointSize;
    // the actual font
    self.fontMax = [UIFont fontWithName:self.fontMax.fontName size:actualFontSize];
    

    my code works great, part from @Igor

提交回复
热议问题