LoginSignup
1
7

More than 5 years have passed since last update.

UITableViewのセルの高さを自動で算出させる

Last updated at Posted at 2017-01-30

↓のスクリーンショットのような感じで、UILabelの行数に依存して、UITableViewのセルの高さが自動で算出されるようにしてみます。

これをやると、 tableView(_:heightForRowAt:) を実装する必要がなくなります。

螢幕快照 2017-01-30 17.03.48.png

TL; DR

  • セルの中のすべてのUIパーツに対して正しいAutoLayoutを設定する
    • 一度UILabelだけのセルにしてみて、うまく伸縮するのを確認してから、1つずつUIパーツを増やしていくのが良い
  • ViewController側で
    • tableView.rowHeight = UITableViewAutomaticDimension と指定する
    • tableView.estimatedRowHeight = 44.0 などと指定する

コードはこちら (Xcode 8, Swift 3)

keisei1092/UITableViewAutomaticDimensionExample
https://github.com/keisei1092/UITableViewAutomaticDimensionExample

参考

[iOS8~]セルの高さ可変UITableView(コードベース)
http://qiita.com/taku_oka/items/c3f9281c4a0c56218c2e

Self-sizing Table View Cells - Ray Wenderlich
https://www.raywenderlich.com/129059/self-sizing-table-view-cells

1
7
0

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
1
7