在查看了所有其他的Stack Overflow表格后,我按照以下方式为我的一个单元格实现了动态高度:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as UITableViewCell
if(indexPath.row == 1){
var image : UIImage = maskRoundedImage(image: UIImage(named: "Temp_Profile.png")!, radius: 150)
cell.imageView?.image = image
return cell
}
cell.textLabel?.text = TableArray[indexPath.row]
cell.backgroundColor = UIColor.init(colorLiteralRed: 0.56, green: 0, blue: 0.035, alpha: 1)
cell.textLabel?.textColor = UIColor.white
cell.textLabel?.font = UIFont(name: "Helvetica", size: 28)
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.row == 1 {
return UITableViewAutomaticDimension * 3
}
return UITableViewAutomaticDimension
}
看起来很简单,但调试会话显示heightForRowAtIndexPath从未被调用。视图控制器是UITableViewController,并且其他所有内容都正常工作。您们中是否有任何人看到此函数未被调用的原因?
感谢您的帮助!
heightForRowAt
可能会很耗费资源;您也可以在viewDidLoad
中调用self.tableView.rowHeight = UITableViewAutomaticDimension
和self.tableView.estimatedRowHeight = 72.0 //estimated, average value
。参见此处的示例:https://www.appcoda.com/self-sizing-cells/。 - koen