• UILabel 根据text的内容来调整大小


    有时候,在UILabel的text过长的时候,我们需要让label进行自适应大小,之前我们必须要获得这个UILabel的size,这便是根据text的内容和性质(字体,行间距等决定的)。 
     
    在ios7中,使用boundingRectWithRect方法来获得CGSize:
     
     
     
    //文字的字体
    NSDictionary *attribute = @{NSFontAttributeName:[UIFont fontWithName:@"Heiti SC" size:15.0f]};
    
     
    //将text转化为NSMutableAttributedString类型
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:_titleLabel.text attributes:attribute];
     
    //设置行间距
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:6.0f];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [_titleLabel.text length])];
     
    //获得UILabel的size,其中,296和93是size的限定值
    CGSize DateSize = [attributedString boundingRectWithSize:CGSizeMake(296, 93) options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading  context:nil].size;
        
    //如果UILabel的宽度太宽的话
    if (DateSize.width > 518.0f/2) 
    { 
        _titleLabel.size = CGSizeMake(296.0f, DateSize.height);
        _titleLabel.textAlignment = NSTextAlignmentLeft;
        _titleLabel.lineBreakMode = NSLineBreakByCharWrapping;
        _titleLabel.numberOfLines = 0;  //不限定行数,自动换行
        _titleLabel.attributedText = attributedString;
    }
  • 相关阅读:
    软件开发流程实例之四 :编码和测试
    软件开发流程实例之三 :系统设计
    jQuery入门[4]-链式代码
    jQuery入门[1]-构造函数
    jQuery入门[2]-选择器
    自编类库,添加引用,编译运行时显示“未能找到”
    SelectByShape 工具的实现
    TOC控件不显示内容列表
    鹰眼功能的实现(步骤,无代码)
    INumericFormat 接口
  • 原文地址:https://www.cnblogs.com/rambot/p/3864263.html
Copyright © 2020-2023  润新知