最新消息:iOS编程开发交流群(6906921) ,Mac.Cocoa开发交流群(7758675) 欢迎iOS/macOS开发编程爱好及学习者加入!

UILabel固定尺寸, 自适应字体大小

iOS 天狐 25921浏览 3评论

UILabel自适应宽高,实现内部字体自动改变大小,使内容全部显示

- (void)setFontSizeThatFits:(UILabel*)label
{

    CGFloat fontSizeThatFits;
    
    [label.text sizeWithFont:label.font
                 minFontSize:12.0   //最小字体
              actualFontSize:&fontSizeThatFits
                    forWidth:label.bounds.size.width
               lineBreakMode:NSLineBreakByWordWrapping];
    
    label.font = [label.font fontWithSize:fontSizeThatFits];
  
}

还有一种方法
label.adjustsFontSizeToFitWidth = YES;
这一句话就可以了
adjustsFontSizeToFitWidth 实现原理:
self.label1.text = @"1234567890qwertyuiopasdfghjklzxcvbnm";
self.label1.font =   [self adjustsFontSize:self.label1];
- (UIFont*)adjustsFontSize:(UILabel*)label{
    float curFontSize = label.font.pointSize;
    UIFont *font = label.font;
    
    CGRect rect;
    rect = [label bounds];
    if (rect.size.width == 0.0f || rect.size.height == 0.0f) {
        return 0;
    }
    
    while (curFontSize > label.minimumScaleFactor && curFontSize > 0.0f) {
        CGSize size = CGSizeZero;
        
        //  A single line of text should be clipped
        if (label.numberOfLines == 1) {
            size = [label.text sizeWithFont:font constrainedToSize:CGSizeMake(rect.size.width, 0.0f) lineBreakMode:NSLineBreakByClipping];
//            size = [label.text boundingRectWithSize:CGSizeMake(rect.size.width, 0.0f)
//                                                  options:NSStringDrawingUsesFontLeading
//                                               attributes:@{NSFontAttributeName: _font}
//                                                  context:NULL].size;
    
        } else {
            //Multiple lines of text should be wrapped
            size = [label.text sizeWithFont:font constrainedToSize:CGSizeMake(rect.size.width, 0.0f) lineBreakMode:NSLineBreakByWordWrapping];
          
        }
        
        if (size.width < rect.size.width && size.height <= rect.size.height) {
            break;
        }
        
        curFontSize -= 1.0f;
        font = [font fontWithSize:curFontSize];
    }
    
    if (curFontSize < label.minimumScaleFactor) {
        curFontSize = label.minimumScaleFactor;
    }
    if (curFontSize < 0.0f) {
        curFontSize = 1.0f;
    }
    
    font = [font fontWithSize:curFontSize];
    
    return font;
}

转载请注明:天狐博客 » UILabel固定尺寸, 自适应字体大小

微信 OR 支付宝 扫描二维码
为天狐 打赏
非常感谢你的支持,哥会继续努力!
发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

网友最新评论 (3)

  1. - (CGSize)sizeWithFont:(UIFont *)font minFontSize:(CGFloat)minFontSize actualFontSize:(CGFloat *)actualFontSize forWidth:(CGFloat)width lineBreakMode:(NSLineBreakMode)lineBreakMode NS_DEPRECATED_IOS(2_0, 7_0);使用这个方法,提示“first deprecated in iOS 7.0”,如何解决?
    crystal11年前 (2015-03-19)回复
    • label.adjustsFontSizeToFitWidth = YES; 这一句话就可以了
      天狐Sky11年前 (2015-03-25)回复