zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    网络字节序与主机字节序
    Maven2插件开发详解
    NetBeans 时事通讯(刊号 # 30 Oct 15, 2008)
    NetBeans 时事通讯(刊号 # 30 Oct 15, 2008)
    Grsync:rsync 的图形化界面
    Windows Socket网络编程学习笔记一
    如何调试MFC中的内存泄漏
    内存池(MemPool)技术详解
    These codes are How to use Lucence.net
    VC控制台程序的文字颜色
  • 原文地址:https://www.cnblogs.com/rambot/p/3864263.html
Copyright © 2011-2022 走看看