Ios TableView-未调用RowAtIndexPath的高度
在浏览了所有其他堆栈溢出表单之后,我为我的一个单元格实现了动态高度,如下所示:Ios TableView-未调用RowAtIndexPath的高度,ios,swift,uitableview,heightforrowatindexpath,Ios,Swift,Uitableview,Heightforrowatindexpath,在浏览了所有其他堆栈溢出表单之后,我为我的一个单元格实现了动态高度,如下所示: override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as UITableViewCe
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
}
这看起来很简单,但调试会话显示HeightForRowatineXpath从未被调用。视图控制器是一个UITableViewController,其他一切都正常工作。你们中有人看到这个函数没有被调用的原因吗
谢谢你的帮助 在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
}
对我来说,我必须这样做
self.tableviewObj.delegate = self
所以,不要忘记将委托添加到self。因为HeightForRowatineXparth是在委托协议中声明的 如果您在
UITableViewController
中,请记住该方法必须是您需要覆盖的方法,否则方法名称错误
在我的例子中,我使用了nsindepath
而不是indepath
,并且它与要调用的正确方法不匹配
tableView(_ tableView: UITableView, heightForRowAt indexPath: NSIndexPath) -> CGFloat
当我把它改成
tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
xcode将提示插入
override
关键字。在我的例子中,我有三个控制器A、B、C。A是基本控制器,B继承自A,C继承自B。我在A中设置tableView委托,并在B中实现heightForRowAt函数,当我使用C时,问题就出现了。我想是因为在A中指定的代理最终指向C,所以不会调用B中的方法。对于试图使用UITableViewAutomaticDimension*3的任何人,请不要这样做。它将-1作为信号返回给tableView,使其成为默认值。使用一个实际的数字。当您从其他地方复制示例时,很容易得到这些方法的旧签名,就像我们大家做的一样!。在某些情况下,如果Swift已经移动到足以使事情无效的程度,XCode将生成一个错误-但对于这种情况,您只会得到一个警告。这就是你不应该忽略那些黄色三角形的原因。Auto complete应该为您提供正确的签名,然后函数的其余部分很可能就可以了。如下所述,UITableViewAutomaticDimension不是一个应该用于算术的值。返回UITableViewAutomaticDimension*3将产生不可预测的影响。请注意,调用heightForRowAt
可能会很昂贵;您还可以调用self.tableView.rowHeight=UITableViewAutomaticDimension
和self.tableView.estimatedRowHeight=72.0//在viewDidLoad
中调用估计的平均值。如果你有新问题,请点击按钮提问。如果你有足够的声誉,问题就来了。或者,“star”将其作为收藏夹,您将收到任何新答案的通知。在这种情况下,(我也是),我发现解决方案是在基类中定义占位符方法调用,然后在子类中重写它。然后它会被调用。