Twitterの投稿をTableViewで表示する場合など、各セルの高さを投稿の長さに応じて変えたい場合があると思います。
例)
そんなときのコード例です。
UI部品の配置
- デフォルトのViewの中にTableViewを追加
- TableViewの中にTableViewCellを追加
- TableViewCellの中にLabelを追加
TableViewCellの設定
- UITableViewCellを継承した新しいクラス(TextCell)を追加しIdentity Inspector→Custom Classで指定する
- カーソルをLabelにあてて、Ctrlキーを押しながらTableViewCellクラスにドロップ。コネクションを設定する
- Attribute Inspector→Table View Cell→Identifierに識別子(textCell)を設定
import UIKit class TextCell: UITableViewCell { @IBOutlet weak var label: UILabel! }
Labelの設定
- Attribute Inspector→Label→Linesをゼロに設定
- Labelの上下左右にスペースのConstraintを設定
ViewControllerの設定
- カーソルをTableViewに合わせてCtlキーを押しながらViewControllerにドラッグ。コネクションを設定する
- viewDidLoad内でtableView.rowHeightにUITableViewAutomaticDimensionにセット。tableView.estimatedRowHeightも適当な値をセットしておく
- UITableViewDataSourceとUITableViewDelegateを継承
- UITableViewDataSourceプロトコルのメソッドを実装
- UITableViewDelegateプロトコルのメソッドを実装
import UIKit class TableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! let textList:[String] = [ "Hello World", "Hello World\nHello World\nHello World\nHello World\nHello World\n", "Hello World", "Hello World\nHello World\nHello World\n", "Hello World\nHello World\n"] override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self tableView.estimatedRowHeight = 100.0 tableView.rowHeight = UITableViewAutomaticDimension } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } //UITableViewDataSourceプロトコルの必須メソッド //テーブルの行数を返す func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return textList.count } //UITableViewDataSourceプロトコルの必須メソッド //指定行のセルデータを返す internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "textCell", for: indexPath) as? TextCell else { return UITableViewCell() } cell.label.text = textList[indexPath.row] return cell } //UITableViewDelegateプロトコルの必須メソッド //行をタップされたときに呼ばれる func tableView(_ tableView: UITableView, didSelectRowAt indexPath:IndexPath) { print(textList[indexPath.row]) } }