UITableViewCellのheightを変更する方法を調べたのでメモ。
Contents
なぜheightを変更する必要があるのか?
twitterを例に考えてみましょう。
タイムラインですね。
行数がどれくらいか?
画像があるのか?
それらの条件でcellの高さを変更したいですよね。フィットさせたいですよね。
heightを動的に変更する方法
まず大切なことは3つあります。
- Autolayout
- estimatedRowHeight
- rowHeight
これらです。
①Autolayout
Storyboardを開きましょう。
UITableViewまたはUITableViewControllerを準備してある前提で進めます。
UITableView,UITableVeiwControllerをご存じない方は、
こちらをご参考にしてください。
swift3:超初心者向け!UITableViewControllerの使い方(1)
swift3:初心者向け!UITableViewの使い方:delegate・datasourceについて
それでは進めていきます。
- CellにUILabelを配置する。この時しっかりとCellの中にUILabelを配置する必要がある。
- UILabelにAutolayoutを設定。左右10、上下5に指定。
- attributes inspectorにてLinesを0に設定。(デフォルトでは1になっているはずです)
- 最後にupdate framesをする。
①の理由
Autolayoutで失敗するから。
②の理由
数字は正直適当。
UILabelにAutolayoutを設定することで、どのような大きさのcellにも対応できるようになった。
これは逆に考えると、UILabelが大きくなったらcellも大きくなるということになる。今回のミソである。
③の理由
今回、UILabelに入れる文字列は1行ではなく、複数に渡る。cellのheightの変化を見たいからだ。
Linesを1に設定していると1行しか表示できない。
0に設定するとなぜか、複数行とりあつかうことができる。


これで第一段階終了です。
estimatedRowHeight
tableView.estimatedRowHeight = 40
これは初期段階のcellの高さを設定します。
正直なぜこれが必要なのかわからないが、これがないと動かないんですよね。
今回は40に設定しました。
rowHeight = UITableViewAutomaticDimension
tableView.rowHeight = UITableViewAutomaticDimension
このように指定する。
これによって各cellが別々のheightを持つことができるようになる。
cellの大きさをAutomaticに変化させることができる。
最終的なコード
import UIKit class TableViewController: UITableViewController { let languages = ["Swift\nSwift\nSwift","Ruby","PHP","C","Java"] override func viewDidLoad() { super.viewDidLoad() tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 40 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return languages.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell cell.label.text = languages[indexPath.row] return cell } }
こんな感じになれば成功です。
質素ですね・・・
しかもcellのheightの変化がわかりづらい・・・これでも変化してるんですよ!
おまけ:Swift\nSwift\nSwiftの解説
この『\n』という謎。
これは改行を表しています。これによって実際にsimulatorでは見えなくなり、改行されます。
文字列の中に使えるので便利ですね。
『正規表現』
とかいう闇の深い分野らしいです。