运行平台: iOS 7.1.2
编辑器: Xcode 6 GM 语言: Swift
iOS创建一个列表很容易,直接使用Table View
即可。但是,一般的单元格高度在设定后,就固定了。有些需求可能需要单元格高度随内容多少而变化 。比如单元格有一个UILabel
, 希望其高度随其内容变化,行数不固定。
动态单元格基本原理
- 正确地设置constraints
- 自定义单元格类
- 重写
tableView: heightForRowAtIndexPath
这个方法
分析
首先,必须要把约束条件弄好,这个是最重要的一步!可以参考文章结尾的引用。
基本可以总结为: 不要限定宽高,上下左右其它元素距离设置清楚 。 PS:有些时候,使用Suggested Constraints似乎也不错。第二步,自定义单元格。自定义的类中需要关注的是重写一个方法layoutSubviews,如下:
override func layoutSubviews() { super.layoutSubviews() // Make sure the contentView does a layout pass here so that its subviews have their frames set, which we // need to use to set the preferredMaxLayoutWidth below. self.contentView.setNeedsLayout() self.contentView.layoutIfNeeded() // 这句非常重要,设置真实的布局宽度 self.detailLabel.preferredMaxLayoutWidth = CGRectGetWidth(self.detailLabel.frame)}
第三步,重写ViewController中的获取单行高度的方法,如下:
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { var handleCell: CustomCell? = tableView.dequeueReusableCellWithIdentifier("MyCell") as? CustomCell var cell: CustomCell if (handleCell != nil) { cell = handleCell! } else { cell = CustomCell() } // 这里设置单元格内容 cell.detailLabel.text = "...你的内容..." cell.setNeedsUpdateConstraints() cell.updateConstraintsIfNeeded() cell.bounds = CGRectMake(0.0, 0.0, CGRectGetWidth(tableView.bounds), CGRectGetHeight(cell.bounds)) cell.setNeedsDisplay() cell.layoutIfNeeded() var size = cell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize) return size.height + 1;}
OK,基本到这里就应该可以做出一个单元格动态高度的列表了。
当然,如果你出错了,可以参看下面的引用。上面的方法是我对下面这些引用作的一个简洁的总结,未经过多测试,不保证绝对正确性。
引用
这些引用都稍显繁琐,按自己所需取吧!