LoginSignup
200

More than 5 years have passed since last update.

SwiftでUITableViewCellの高さを動的に変更する

Last updated at Posted at 2014-09-21

iOS8では以前と比べて簡単にUITableViewCellの高さを動的に変更することが可能となった。

スクリーンショット 2014-09-21 10.51.04.png

Xcode6.0からStoryboardのレイアウト方法が大幅に改善され、Autolayoutをバンバン使っていく流れになると思うので、ここでもAutolayoutを使用して作業を進めていく。

以前のようにHeightを計算する作業がなくなりStoryboard上で全ての作業を終えることが出来るのは本当にありがたい。

Storyboardでの設定

Cell上に好きなように要素を配置して、高さが可変なUILabelのLinesを0にする。
これでUILabelが複数行対応となる。

スクリーンショット 2014-09-21 10.25.25.png

次に、可変となるUILabelにConstraintsを設定する。
具体的には周りの要素との距離を設定するだけ。

スクリーンショット 2014-09-21 10.28.31.png

Storyboardでの設定は以上。

ViewControllerでの記述

self.tableView.estimatedRowHeightにはStoryboard上でのCellの高さを入力すればいい。
大事なのはself.tableView.rowHeight = UITableViewAutomaticDimensionで、これでCellの高さを自動的に決定するようになる。

これが大事
self.tableView.estimatedRowHeight = 90
self.tableView.rowHeight = UITableViewAutomaticDimension

ViewControllerの中身

ViewController
class ViewController: UIViewController {
    @IBOutlet weak var tableView: UITableView!
    var articles: Array<Article>?

    override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView.estimatedRowHeight = 90
        self.tableView.rowHeight = UITableViewAutomaticDimension

        articles = [
        Article(title: "私わたくしはその人を常に先生と呼んでいた。だからここでもただ先生と書くだけで本名は打ち明けない。", userName: "夏目漱石"),
        Article(title: "この書の世に出づるにいたりたるは、函館にある秦慶治氏、及び信濃にある神津猛氏のたまものなり。労作終るの日にあたりて、このものがたりを二人の恩人のまへにさゝぐ。", userName: "島崎藤村"),
        Article(title: "散文に二種あると考へてゐるが、一を小説、他を作文とかりに言つておく。", userName: "坂口安吾"),
        Article(title: "機敏な晩熟児といふべき此の男が、現に存するのだから僕は機敏な晩熟児が如何にして存るママかその様を語らうと思ふ。", userName: "中原中也")
        ]
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int  {
        return articles!.count
    }

    func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath:NSIndexPath!) -> UITableViewCell! {
        let cell: MyTableViewCell = tableView?.dequeueReusableCellWithIdentifier("Cell") as MyTableViewCell
        cell.article = articles?[indexPath.row]
        cell.layoutIfNeeded()
        return cell;
    }
}

終わり。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
200