IOS开发之UILabel动态高度设置方法
项目中有这样的需求,要显示一本书的概述,默认显示2行,点击展开按钮,显示全部,点击收回,有显示2行。
开始的时候按钮事件中,可能写的是这样一段代码:
if (isExpand) {
[lblBrief setNumberOfLines:2];
lblBrief.text = [StringUtil subString:strBrief AndSubLength:90];
[btnBrief setImage:[UIImage imageNamed:@"detailBriefDown"] forState:UIControlStateNormal];
[btnBrief setImage:[UIImage imageNamed:@"detailBriefDown"] forState:UIControlStateHighlighted];
}else{
[lblBrief setNumberOfLines:0];
lblBrief.text = strBrief;
[btnBrief setImage:[UIImage imageNamed:@"detailBriefUp"] forState:UIControlStateNormal];
[btnBrief setImage:[UIImage imageNamed:@"detailBriefUp"] forState:UIControlStateHighlighted];
}
可以通过setNumberOfLines:0,来让概述的所以内容显示出来,但如果,不计算所要显示全部内容的总高度,label的宽高是不会自动增大的。
else{
[lblBrief setNumberOfLines:0];
lblBrief.text = strBrief;
CGSize constraint = CGSizeMake(self.view.frame.size.width - (15 * 2), 20000.0f);
CGSize size = [strBrief sizeWithFont:[UIFont systemFontOfSize:10]constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
[brief setFrame:CGRectMake(15,160,size.width,size.height)];
[btnBrief setImage:[UIImage imageNamed:@"detailBriefUp"]forState:UIControlStateNormal];
[btnBrief setImage:[UIImage imageNamed:@"detailBriefUp"]forState:UIControlStateHighlighted];
}