しめ鯖日記

swift, iPhoneアプリ開発, ruby on rails等のTipsや入門記事書いてます

UITableViewのCellの高さを自動調整してくれるUITableViewAutomaticDimension

UITableViewAutomaticDimensionという機能を使えばheightForRowAtIndexPathが不要なるらしいので試してみました。

使い方

StoryboardでCellの中にLabelをAutoLayout付きで入れます。

f:id:llcc:20151203002019p:plain

次にコードでtableViewのrowHeightにUITableViewAutomaticDimension、estimatedRowHeightに適当な値を入れます。

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.estimatedRowHeight = 20
    tableView.rowHeight = UITableViewAutomaticDimension
}

最後にCellのLabelに複数行のテキストを入れます。

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)

    let text = (0...indexPath.row).map { _ in "AAA" }.joinWithSeparator("\n")
    (cell.viewWithTag(10) as? UILabel)?.text = text
    
    return cell
}

実行結果

下のように可変なCellが作れました。

f:id:llcc:20151203002308p:plain

左右のAutoLayoutを設定すれば長い文字列も自動で複数行になってくれます。

f:id:llcc:20151203002455p:plain

UITextViewはscrollEnabledをfalseにすれば同様の動きをしてくれました。

f:id:llcc:20151203002853p:plain

参考URL

UITableViewCellの高さを自動で計算する: UITableViewAutomaticDimension - tomoyaonishiのブログ