在浏览了所有其他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。 View Controller是一个UITableViewController,其他一切都正常工作。你们有没有看到没有调用此函数的原因?
感谢您的帮助!
答案 0 :(得分:13)
在Swift 3中,签名是:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
您拥有旧签名,因此无法识别。
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row == 1 {
return UITableViewAutomaticDimension * 3
}
return UITableViewAutomaticDimension
}
答案 1 :(得分:3)
对我来说,我必须这样做。
self.tableviewObj.delegate = self
所以,不要忘记给自己添加代表。因为heightForRowAtIndexparth是在委托协议中声明的。
答案 2 :(得分:0)
如果您位于UITableViewController
内,请记住该方法必须是override
所需要的方法,否则该方法的名称错误。
在我的情况下,我使用的是NSIndexPath
而不是IndexPath
,它与要调用的正确方法不匹配
tableView(_ tableView: UITableView, heightForRowAt indexPath: NSIndexPath) -> CGFloat
我将其更正为
tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
xcode会提示您插入override
关键字。
答案 3 :(得分:0)
在我的情况下,我有三个控制器A,B,C。A是基本控制器,B从A继承,C则从B继承。我在A中设置tableView委托,并在B中实现heightForRowAt函数,并且存在问题当我使用C时发生。我猜是因为A中分配的代理最终指向C,所以未调用B中的方法。