我已经定义了一个自定义 UITableViewCell,在 UITableViewController 中使用,它显示在我的表格中。问题是单元格保留了原始高度,作为默认的 UITableViewCell,而不是使用我在“大小检查器”->“表格 View 单元格”->“行高”中指定的高度。
我的自定义单元格加载如下:
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
最佳答案
如果您的 tableview 单元格数据是静态的并且每个单元格的高度相同,请覆盖此函数(如果您使用 UITableViewController
子类)以返回单元格的高度。
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 100.0
}
否则,如果您的数据是动态的,并且您希望每个单元格都有自己的高度,请将其设置为
viewDidLoad
方法: tableView.estimatedRowHeight = 44.0
tableView.rowHeight = UITableViewAutomaticDimension
不要忘记对单元格中的所有 View (例如
UILabel
、 UIImageView
等)应用约束以让 tableView
自动计算和调整单元格高度。
关于ios - 确保每个自定义 UITableViewCell 调整单元格高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35821322/