如何根据UITableViewCells的高度调整UITableView的高度?

如何根据UITableViewCells的高度调整UITableView的高度?

问题描述:

我有一个tableview,我设置自动布局到单元格,所以一个单元格的高度可能是50,另一个可能是120.我需要显示最大2个单元格,所以如果count> 2,那么单元格count = 2,否则它等于细胞数量。如何根据UITableViewCells的高度调整UITableView的高度?

我的问题是根据每个单元格大小调整UITableView高度的大小。我该如何正确设置UITableView的高度约束值?

我希望我可以解释我想要什么,如果您有任何疑问,请咨询我

+0

是文本内容的动态 –

+0

装入表视图数据和tableview.layoutIfNeeded力布局。那么你可以设置:tableviewHeightContraint.constant = tableview.contentSize.height – stefos

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 
    if indexPath.row == 0 { 
     return 50 
    } else { 
     return 120 
    } 
} 

不要设置高度明确。使用这个:

tableView.estimatedRowHeight = 100 
tableView.rowHeight = UITableViewAutomaticDimension 
+0

这是为了适应只有单元格高度不是表格视图高度 –

+0

你的意思是表格视图的内容大小?当您使用自动布局时,tableview内容大小会自动更新。 –

+0

编号我的意思是说表视图高度 –

尝试在计算高度时将UITableViewCell高度存储在数组中。

如果您手动计算高度,请将高度存储在数组中。 如果你正在自动调整细胞高度,获取细胞,然后它的高度,并将其存储在一个阵列

看看我发布在这个*文章的代码。

Dynamic height

您只需添加一个静态函数你UITableViewCell,其中“措施本身”,那么你存储在一个“行高度”变量。

+(CGSize)preferredSize 
{ 
    static NSValue *sizeBox = nil; 
    static dispatch_once_t onceToken; 
    dispatch_once(&onceToken, ^{ 
     // Assumption: The XIB file name matches this UIView subclass name. 
     NSString* nibName = NSStringFromClass(self); 
     UINib *nib = [UINib nibWithNibName:nibName bundle:nil]; 

     // Assumption: The XIB file only contains a single root UIView. 
     UIView *rootView = [[nib instantiateWithOwner:nil options:nil] lastObject]; 

     sizeBox = [NSValue valueWithCGSize:rootView.frame.size]; 
    }); 
    return [sizeBox CGSizeValue]; 
} 

(你会认为,现在,在2016年,苹果就已经有这样做的一个简单的方法为我们提供了...)

如果您的iOS目标为> = 8,那么你就可以让你的tableview单元格调整没有太大的痛苦。

//provide the estimated height of your cell row over here 
self.tableView.estimatedRowHeight = 60 
self.tableView.rowHeight = UITableViewAutomaticDimension 

不要忘记为单元格的内容视图中的所有视图放置顶部,底部,左侧,右侧约束。

尝试下面的代码它的作品了

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 
    return UITableViewAutomaticDimension 
} 

func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 
    return UITableViewAutomaticDimension 

}