如何制作自动调整大小(高度)UITableViewCell?

时间:2014-08-14 10:53:23

标签: ios xcode uitableview autolayout

请告诉我如何让单元格根据行数自动更改高度?

enter image description here

1 个答案:

答案 0 :(得分:1)

iOS8 中,它将自动为您管理

http://www.shinobicontrols.com/blog/posts/2014/07/24/ios8-day-by-day-day-5-auto-sizing-table-view-cells

iOS7 / 6 中,您可以使用autolayout执行此操作。您可以创建单元格来设置所需的约束。在您的情况下,您可以将标签附加到超级视图的顶部,底部,尾部和前导。

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath中,您可以使用[cell systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];来获取单元格的最小尺寸。例如:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomCell *cell = self.layoutTableViewCell;

    [cell configureWithText:text];

    CGSize layoutSize =  [cell systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];

    return layoutSize.height;
}

请记住,要避免为UILabel设置宽度和高度限制,它会自动调整大小以适应内容。

您可以使用以下方法在viewDidLoad中创建self.layoutTableViewCell

    UINib *cellNib = [UINib nibWithNibName:CustomCellNibName bundle:nil];
    self.layoutTableViewCell = [[cellNib instantiateWithOwner:nil options:nil] objectAtIndex:0];
OT:我认为这是个人品味的问题。我个人开始总是使用UICollectionViews,只是为了重用更多的代码,如果将来我需要自定义布局行为,就会有更大的灵活性。