TableView - heightForRowAtIndexPath未被调用

7

在查看了所有其他的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,并且其他所有内容都正常工作。您们中是否有任何人看到此函数未被调用的原因?

感谢您的帮助!


如下所述,UITableViewAutomaticDimension不应用于算术运算。返回UITableViewAutomaticDimension * 3将产生不可预测的影响。 - GetSwifty
请注意,调用heightForRowAt可能会很耗费资源;您也可以在viewDidLoad中调用self.tableView.rowHeight = UITableViewAutomaticDimensionself.tableView.estimatedRowHeight = 72.0 //estimated, average value。参见此处的示例:https://www.appcoda.com/self-sizing-cells/。 - koen
4个回答

18

在 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
}

3
如果有人尝试使用UITableViewAutomaticDimension * 3,请不要这样做。它只会返回-1,作为让tableView采用默认行高的信号。请使用实际的数字。 - Code Wiget
1
当你从其他地方复制示例时,很容易出现这些方法的旧签名 - 我们都会这样做!在某些情况下,如果Swift已经足够发展而使事情无效,XCode将生成错误 - 但对于这种情况,您只会收到警告。这就是为什么您不应忽略那些黄色三角形的原因。自动完成应该给出正确的签名,然后函数的其余部分很可能是正确的。 - Russell

16

对我而言,我必须这样做。

self.tableviewObj.delegate = self
所以,不要忘记将代理添加到self中。因为heightForRowAtIndexpath在代理协议中声明。

是的,在viewDidLoad方法中添加上面的代码后,它起作用了。谢谢。 - user1090751

1
在我的情况下,我有三个控制器 A、B、C。A 是基础控制器,B 继承自 A,C 继承自 B。我在 A 中设置了 tableView 代理,并在 B 中实现了 heightForRowAt 函数,在使用 C 时出现了问题。我猜测是因为在 A 中分配的代理最终指向了 C,所以 B 中的方法没有被调用。

如果您有新的问题,请点击提问按钮进行提问。如果您拥有足够的声望,您可以投票支持该问题。或者,将其标记为收藏夹中的“星标”,您将收到任何新答案的通知。 - Johan
在这种情况下,(我也是),我发现解决方法是在基类中定义一个占位符方法调用,然后在派生类中重写它。然后它就会被调用。 - Paul Stevenson

0

如果你在一个UITableViewController中,要记住方法必须是需要override的或者方法名错误。

在我的情况下,我使用了NSIndexPath而不是IndexPath,导致无法调用正确的方法。

tableView(_ tableView: UITableView, heightForRowAt indexPath: NSIndexPath) -> CGFloat

当我将其纠正为

tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat

Xcode 会提示插入 override 关键字。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接