确保每个自定义UITableViewCell调整单元格高度?

时间:2016-03-05 23:45:55

标签: ios xcode uitableview swift2

我已经定义了一个自定义的UITableViewCell,在UITableViewController中使用,它在我的表中显示。问题是单元格保留原始高度,作为默认的UITableViewCell,而不是使用我在“大小检查器”中指定的高度 - > “表格视图单元格” - > “行高”。

我的自定义单元格按如下方式加载:

tableView.registerNib(UINib(nibName: "CustomTableViewCell", bundle: nil), forCellReuseIdentifier: "Cell")

然后在tableView函数中:

let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CustomTableViewCell
cell.titleLabel?.text = "title text"
cell.detailTextLabel?.text = "detail text to go here"

我曾尝试按如下方式手动设置高度,但这也不起作用:

cell.frame.size.height = 100.0

正确的方法让细胞处于正确的高度?

XCode 7.2.1,iOS 9

4 个答案:

答案 0 :(得分:4)

如果您的tableview单元格数据是静态的并且每个单元格的高度相同,则覆盖此函数(如果使用UITableViewController子类)以返回单元格的高度。

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

否则,如果您的数据是动态的,并且您希望每个单元格都有自己的高度,请在viewDidLoad方法中设置:

   tableView.estimatedRowHeight = 44.0
   tableView.rowHeight = UITableViewAutomaticDimension 

不要忘记对单元格中的所有视图(例如UILabelUIImageView等)应用约束,让tableView自动计算并调整单元格高度。

答案 1 :(得分:0)

行高是的属性。在您的表视图控制器的viewDidLoad中,可能就在您已经说过的地方:

tableView.registerNib(UINib(nibName: "CustomTableViewCell", bundle: nil), forCellReuseIdentifier: "Cell")

也这样说:

tableView.rowHeight = 100

答案 2 :(得分:0)

TableView.estimatedRowHeight 

有意义的事情

确保您的约束允许正确调整大小。这是最重要的部分。如果你做不到,还有更多的方法。但你不想去那里。这是迄今为止最方便的方法

不要使用rowHeight或相关的委托/数据源函数

答案 3 :(得分:0)

在Obj C中,您可以在UITableViewController子类中实现此功能:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100; // or whatever your cell height is
}

也许在Swift中有一个等价物

相关问题