[Swift4/iOS] TableViewで高さの違うセルを表示する

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)を設定

[swift title=”TextCell.swift”]
import UIKit

class TextCell: UITableViewCell {

@IBOutlet weak var label: UILabel!
}
[/swift]

Labelの設定

  • Attribute Inspector→Label→Linesをゼロに設定
  • Labelの上下左右にスペースのConstraintを設定

ViewControllerの設定

  • カーソルをTableViewに合わせてCtlキーを押しながらViewControllerにドラッグ。コネクションを設定する
  • viewDidLoad内でtableView.rowHeightにUITableViewAutomaticDimensionにセット。tableView.estimatedRowHeightも適当な値をセットしておく
  • UITableViewDataSourceとUITableViewDelegateを継承
  • UITableViewDataSourceプロトコルのメソッドを実装
  • UITableViewDelegateプロトコルのメソッドを実装

[swift title=”TableViewController.swift”]
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])
}
}

[/swift]

kaizawa

闘う兼業主夫プログラマー。外資系IT企業所属。C++、Java、Solaris、Oracle、セキュリティ、DLP(Data Loss Prevention)、D&D、空手二段(極真会館)、柔道初段、柔術白帯ストライプ3(トライフォース)。English/中文

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です