有时候,在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; }