假设我在UILabel中有以下文本(一长行动态文本):
由于外星军队的数量远远超过了团队,玩家必须利用后世界末日的优势,比如在垃圾箱、柱子、汽车、瓦砾和其他物体后面寻找掩护。
我想调整UILabel的高度,这样文本就可以放进去了。我使用以下属性的UILabel,使文本内包装。
myUILabel.lineBreakMode = UILineBreakModeWordWrap;
myUILabel.numberOfLines = 0;
如果我的方向不对,请告诉我。谢谢。
假设我在UILabel中有以下文本(一长行动态文本):
由于外星军队的数量远远超过了团队,玩家必须利用后世界末日的优势,比如在垃圾箱、柱子、汽车、瓦砾和其他物体后面寻找掩护。
我想调整UILabel的高度,这样文本就可以放进去了。我使用以下属性的UILabel,使文本内包装。
myUILabel.lineBreakMode = UILineBreakModeWordWrap;
myUILabel.numberOfLines = 0;
如果我的方向不对,请告诉我。谢谢。
当前回答
当自动布局被启用时,调整大小不工作:)
其他回答
更新方法
+ (CGFloat)heightForText:(NSString*)text font:(UIFont*)font withinWidth:(CGFloat)width {
CGSize constraint = CGSizeMake(width, 20000.0f);
CGSize size;
CGSize boundingBox = [text boundingRectWithSize:constraint
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:font}
context:nil].size;
size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height));
return size.height;
}
此方法适用于iOS 6和7
- (float)heightForLabelSize:(CGSize)maximumLabelSize Font:(UIFont *)font String:(NSString*)string {
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
NSDictionary *stringAttributes = [NSDictionary dictionaryWithObject:font forKey: NSFontAttributeName];
CGSize adjustedLabelSize = [string maximumLabelSize
options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin
attributes:stringAttributes context:nil].size;
return adjustedLabelSize.height;
}
else {
CGSize adjustedLabelSize = [string sizeWithFont:font constrainedToSize:maximumLabelSize lineBreakMode:NSLineBreakByWordWrapping];
return adjustedLabelSize.height;
}
}
谢谢你写这篇文章。这对我帮助很大。在我的例子中,我也在一个单独的视图控制器中编辑文本。我注意到当我使用:
[cell.contentView addSubview:cellLabel];
在tableView:cellForRowAtIndexPath:方法中,每当我编辑单元格时,标签视图不断地在前一个视图之上呈现。文本变得像素化,当某些内容被删除或更改时,旧版本在新版本下可见。下面是我解决这个问题的方法:
if ([[cell.contentView subviews] count] > 0) {
UIView *test = [[cell.contentView subviews] objectAtIndex:0];
[test removeFromSuperview];
}
[cell.contentView insertSubview:cellLabel atIndex:0];
不再有奇怪的分层。如果有更好的处理方法,请告诉我。
最后,它成功了。谢谢大家。
我没有让它工作,因为我试图在heightForRowAtIndexPath方法中调整标签的大小:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
和(是的,我很傻),我在cellForRowAtIndexPath方法中调整标签的默认大小-我忽略了我之前写的代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
sizeWithFont constrainedToSize:lineBreakMode:是使用的方法。如何使用它的例子如下:
//Calculate the expected size based on the font and linebreak mode of your label
// FLT_MAX here simply means no constraint in height
CGSize maximumLabelSize = CGSizeMake(296, FLT_MAX);
CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font constrainedToSize:maximumLabelSize lineBreakMode:yourLabel.lineBreakMode];
//adjust the label the the new height.
CGRect newFrame = yourLabel.frame;
newFrame.size.height = expectedLabelSize.height;
yourLabel.frame = newFrame;