更改tableView单元格内的UILabel框架高度

我从远程URL得到我的UILabel文本,有时文本太短/太长,我需要适应我的框架大小文本高度。 我用xib实现了服装单元格。

截图

这是我到目前为止所尝试的,这应该是有效的,但不工作的理由我不明白:

  cell.fbLastObject.text = [NSString stringWithFormat:@"%@",update.fbLastObject]; [cell.fbLastObject sizeToFit]; //Cell Size CGSize labelSize = [cell.fbLastObject.text sizeWithFont:cell.fbLastObject.font constrainedToSize:cell.fbLastObject.frame.size lineBreakMode:NSLineBreakByWordWrapping]; labelHeight = labelSize.height; cell.fbLastObject.frame = CGRectMake(0,0,300,labelHeight); 

任何人有任何想法?

对于iOS 8 and later ,您可以使用UITableViewAutomaticDimension将以下代码放在viewDidLoad中:

  tableView.rowHeight = UITableViewAutomaticDimension; /* any estimated height but must be more than 2 */ tableView.estimatedRowHeight = 160.0; tableview.delegate = self; tableview.dataSource = self; // you have created the SimpleTableViewCell.xib, So you need to register that cell with table. UINib *nib = [UINib nibWithNibName:@"SimpleTableViewCell" bundle:nil]; [tableview registerNib:nib forCellReuseIdentifier:@"SimpleTableViewCell"]; 

现在添加适当的cell fbLastObject约束(顶部,底部,引导和尾随)引脚超级查看&设置行数为0

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellIdentifier = @"SimpleTableViewCell"; SimpleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath]; // here set text for your cell label cell.fbLastObject.text = @"My Text"; [cell setNeedsLayout]; [cell layoutIfNeeded]; return cell; } 

你可以尝试self.tblView.rowHeight = UITableViewAutomaticDimension;

对于使用自动布局的dynamic单元格

你可以通过映射UILabel的高度约束,并根据计算的高度返回高度计算从远程URL的文本的大小,也给高度映射高度约束出口和返回单元格之前只写: –

[cell.UILabel updateConstraints];

在你的问题,你采取的步骤,以获得标签的大小是好的。 使标签的属性SizeToFit和NumberOfLines为0,并添加适当的约束。 然后为Label的Height约束创build一个NSLayoutConstraint的实例,并将其附加到UITableViewCell的底部。 然后,当你从文本中获得CGSize的时候,你需要调用UpdateConstraintIfNeeded on self,然后需要为该Label的约束设置高度常量属性,需要设置UITableVIew的heightForRowAtIndexpath。 希望这会工作。