假设我在UILabel中有以下文本(一长行动态文本):

由于外星军队的数量远远超过了团队,玩家必须利用后世界末日的优势,比如在垃圾箱、柱子、汽车、瓦砾和其他物体后面寻找掩护。

我想调整UILabel的高度,这样文本就可以放进去了。我使用以下属性的UILabel,使文本内包装。

myUILabel.lineBreakMode = UILineBreakModeWordWrap;
myUILabel.numberOfLines = 0;

如果我的方向不对,请告诉我。谢谢。


当前回答

这种方法可以得到完美的高度

-(float) getHeightForText:(NSString*) text withFont:(UIFont*) font andWidth:(float) width{
CGSize constraint = CGSizeMake(width , 20000.0f);
CGSize title_size;
float totalHeight;


title_size = [text boundingRectWithSize:constraint
                                options:NSStringDrawingUsesLineFragmentOrigin
                             attributes:@{ NSFontAttributeName : font }
                                context:nil].size;

totalHeight = ceil(title_size.height);

CGFloat height = MAX(totalHeight, 40.0f);
return height;
}

其他回答

你的方向是对的。你所需要做的就是:

myUILabel.numberOfLines = 0;
myUILabel.text = @"Enter large amount of text here";
[myUILabel sizeToFit];

最后,它成功了。谢谢大家。

我没有让它工作,因为我试图在heightForRowAtIndexPath方法中调整标签的大小:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

和(是的,我很傻),我在cellForRowAtIndexPath方法中调整标签的默认大小-我忽略了我之前写的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
NSString *str = @"Please enter your text......";
CGSize lblSize = [str sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize: CGSizeMake(200.0f, 600.0f) lineBreakMode: NSLineBreakByWordWrapping];

UILabel *label = [[UILabel alloc]init];
label.frame = CGRectMake(60, 20, 200, lblSize.height);
label.numberOfLines = 0;
label.lineBreakMode = NSLineBreakByWordWrapping;
label.font = [UIFont systemFontOfSize:15];
label.text = str;
label.backgroundColor = [UIColor clearColor];
[label sizeToFit];
[self.view addSubview:label];

你可以使用下面的代码得到高度

你必须通过

文本2。字体3。标签宽度 func hightforlabel (text: String, font: UIFont, width: CGFloat) -> CGFloat { let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude)) 标签。numberolines = 0 标签。lineBreakMode = nslinebreakmode . bywordwrapped 标签。Font = Font 标签。Text = Text label.sizeToFit () 返回label.frame.height }

这种方法可以得到完美的高度

-(float) getHeightForText:(NSString*) text withFont:(UIFont*) font andWidth:(float) width{
CGSize constraint = CGSizeMake(width , 20000.0f);
CGSize title_size;
float totalHeight;


title_size = [text boundingRectWithSize:constraint
                                options:NSStringDrawingUsesLineFragmentOrigin
                             attributes:@{ NSFontAttributeName : font }
                                context:nil].size;

totalHeight = ceil(title_size.height);

CGFloat height = MAX(totalHeight, 40.0f);
return height;
}