我有一个带有自定义UITableViewUITableViewCell,每个都有一个UIButton。我要从数组中设置按钮的标题,因此按钮的大小会根据标题而变化。我需要根据heightForRowAtIndexPath事件中内部按钮的大小返回正确的高度。

由于我使用的是自动布局,因此我为按钮的高度限制创建了一个出口,并在单元格的layoutSubviews()事件中更新了出口,如下所示:

class CustomCell: UITableViewCell {

    /* ... */

    override func layoutSubviews() {
        super.layoutSubviews()
        self.myButton?.layoutIfNeeded()
        self.heightConstraint?.constant = self.myButton!.titleLabel!.frame.size.height
    }
}

然后根据按钮高度和上下边距返回高度,如下所示:
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    var cell = tableView.dequeueReusableCellWithIdentifier("CustomCell") as! CustomCell
    cell.myButton?.setTitle(self.data[indexPath.row], forState: UIControlState.Normal)
    cell.bounds = CGRectMake(0, 0, CGRectGetWidth(tableView.bounds), CGRectGetHeight(cell.bounds))
    cell.setNeedsLayout()
    cell.layoutIfNeeded()
    return cell.myButton!.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height + (cell.topMarginConstraint!.constant * 2) /* top-bottom margins */ + 1 /* separator height */
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCellWithIdentifier("CustomCell") as! CustomCell
    cell.myButton?.setTitle(self.data[indexPath.row], forState: UIControlState.Normal)
    return cell
}

在首次启动时,似乎没有问题。但是,在我开始滚动之后,那么似乎有些行的高度是错误的。回到顶部时,我发现以前的像元高度也被破坏了。

当我用Google搜索类似问题时,问题似乎与可重用单元有关,尽管我无法找到另一种计算高度的方法。可以通过另一种方法做什么以正确地重用单元格或获得正确的高度?

更多信息和源代码:

IB设置的约束如下:

这是第一次启动时的单元格:

滚动后:

该项目的完整代码可以在Github上找到。

最佳答案

根据this

将tableView配置为

func configureTableView() {
  tableView.rowHeight = UITableViewAutomaticDimension
  tableView.estimatedRowHeight = 160.0
}
  • 在您的viewDidLoad方法
  • 上调用它
  • 比将您的uibutton高度约束配置为大于或等于。
  • 覆盖func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat,您可以在其中放置估算高度代码
  • 08-18 09:27
    查看更多