Get the number of lines in UILabel iOS8
I'm seeing lots of deprecated answers for this question:
How do I calculate the number of lines in use in a UILabel
based of its set text?
I know that I need to set the UILabel
to have bounds that resize with word wrapping. In this way, I could detect the height of my UILabel
and adjust an NSLayoutConstraint
for the height of my UITableViewCell
. Basically my problem plain and simple is:
How can I determine my UILabel 's number of lines in use(based of descriptionLabel.text
) or height in order to resize My UITableView 's UITableViewCell s which contain my UILabel .
Currently I have used this code:
descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 30, 270, 65)];
descriptionLabel.textColor = [UIColor blackColor];
descriptionLabel.numberOfLines = 0;
descriptionLabel.adjustsFontSizeToFitWidth = YES;
尝试使用下面的代码
NSAttributedString *attrStr = ... // your attributed string
CGFloat width = 300; // whatever your desired width is
CGRect rect = [attrStr boundingRectWithSize:CGSizeMake(width, 10000) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil];
//rect is the height of UILABEL which u can used as height of label or table view row or etc
我用这段代码很简单地解决了我的问题:
CGSize maxSize = CGSizeMake(290.0f, CGFLOAT_MAX);
CGSize requiredSize = [descriptionLabel sizeThatFits:maxSize];
[descriptionLabel setFrame:CGRectMake(15, 50, requiredSize.width, requiredSize.height)];
NSLog(@"THE HEIGHT OF THIS DESCRIPTIONLABEL IS: %f",cell.frame.size.height);
链接地址: http://www.djcxy.com/p/28208.html
上一篇: 使UIImageView调整大小以适应UILabel与AutoLayout
下一篇: 获取UILabel iOS8中的行数