【发布时间】:2015-06-30 07:24:11
【问题描述】:
我有一个带有自定义UITableViewCells 的UITableView,每个内部都有一个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
}
在第一次启动时,似乎没有问题。但是,在我开始滚动之后,某些行的高度似乎是错误的。当我回到顶部时,我看到之前的单元格高度也被打破了。
当我用谷歌搜索类似的问题时,问题似乎与可重复使用的细胞有关,尽管我无法找到另一种计算高度的方法。可以做些什么来正确重用单元格或获得正确的高度,也许是通过另一种方法?
更多信息和源代码:
IB 设置的约束如下:
这是第一次发布时的单元格:
滚动后:
项目的完整代码可以在Github找到。
【问题讨论】:
标签: ios objective-c swift uitableview autolayout