iOS auto adjust label height

拥有回忆 提交于 2019-12-08 09:07:08

问题


I'm using the following code to auto adjust the height of a label in a UITableView. It works the majority of the time, but certain times text is cut off. Is there something wrong with my code, or anything else I need to add?

UILabel *textLabel = ((UILabel *)[cell viewWithTag:3]);
textLabel.text = text;

CGSize maximumLabelSize = CGSizeMake(296, FLT_MAX);

CGSize expectedLabelSize = [text sizeWithFont:textLabel.font constrainedToSize:maximumLabelSize lineBreakMode:textLabel.lineBreakMode];

//adjust the label the the new height.
CGRect newFrame = textLabel.frame;
newFrame.size.height = expectedLabelSize.height;
textLabel.frame = newFrame;

回答1:


In iOS 7 sizeWithFont: constrainedToSize: lineBreakMode: is deprecated, now you should use:

 CGSize maxSize = CGSizeMake(296.f, FLT_MAX);
 CGRect labRect = [someText boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:textLabel.font} context:nil];


 textLabel.frame = CGRectMake(0, 0, maxSize.width, labRect.size.height);
 textLabel.text = someText;


来源:https://stackoverflow.com/questions/20618275/ios-auto-adjust-label-height

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!