您的位置:首页 > 其它

获取文字高度以及根据label内容来调整label的高度

2014-07-30 13:35 393 查看
ios7以上已经摒弃 sizeWithFont 这个方法,需要用到 boundingRectWithSize 来获取文字的高度


UILabel根据内容自动调整高度

sizeWithFont已经被Apple抛弃了,但还是可以用的


iOS7出来以后,以前的UILabel根据内容获得高度和宽度不建议用了,虽然还可以用,但是总有有强迫症的,不希望有警告,这段代码是iOS7以后UILabel可以根据内容改变高度和宽度。


/*根据label内容来调整label的高度*/

- (void)resizeLabelByContent:(UILabel *)label

{

CGSize maxSize = CGSizeMake(label.width, 999);

label.numberOfLines = 0;

NSString *contentStr = label.text;

UIFont *contentFont = label.font;

CGRect contentFrame;

NSString *version = [[UIDevice currentDevice] systemVersion];

if ([version floatValue] < 7.0) {

CGSize contentStringSize = [contentStr sizeWithFont:contentFont constrainedToSize:maxSize lineBreakMode:label.lineBreakMode];

contentFrame = CGRectMake(label.left, label.top, label.width, contentStringSize.height);

} else {

NSDictionary *contentDic = [NSDictionary dictionaryWithObjectsAndKeys:contentFont, NSFontAttributeName, nil];

CGSize contentStrSize = [contentStr boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:contentDic context:nil].size;

contentFrame = CGRectMake(label.left, label.top, label.width, contentStrSize.height);

}

label.frame = contentFrame;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: