您的位置:首页 > 产品设计 > UI/UE

iOS中的UILabel自动计算高度和换行

2016-07-20 00:00 411 查看
UILabel自动计算高度和换行

self.dizhiLabel = [[UILabel alloc]init];
self.dizhiLabel.textColor = [UIColor grayColor];
//折行
self.dizhiLabel.lineBreakMode = NSLineBreakByWordWrapping;
//必须写,否则只显示一行
[ self.dizhiLabel setNumberOfLines:0];
[self.contentView addSubview: self.dizhiLabel];
[ self.dizhiLabel mas_makeConstraints:^(MASConstraintMaker *make) {

make.left.equalTo(self.zuobiaoImageView.mas_right).offset(20);
make.right.equalTo(self.contentView.mas_right).offset(-20);
make.top.equalTo( self.zuobiaoImageView.mas_top);

}];

//根据文字内容和字体计算高度
CGSize textSize = CGSizeZero;
// 多行必需使用NSStringDrawingUsesLineFragmentOrigin,网上有人说不是用NSStringDrawingUsesFontLeading计算结果不对
NSStringDrawingOptions opts = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;

NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
[style setLineBreakMode:NSLineBreakByCharWrapping];

NSDictionary *attributes = @{ NSFontAttributeName : [UIFont systemFontOfSize:17], NSParagraphStyleAttributeName : style };

CGRect rect = [ self.dizhiLabel.text boundingRectWithSize:(CGSize){ self.dizhiLabel.frame.size.width, MAXFLOAT}
options:opts
attributes:attributes
context:nil];
textSize = rect.size;

self.dizhiLabel.frame = CGRectMake(85, 15, textSize.width, textSize.height);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: