UITableViewCellの高さを自動調整させる方法をメモ。
1. storyboardでViewControllerにTableViewを設置する
今回は、TableViewにTableViewCellを3つ配置。各セル内にラベルを置く。
2. セル内のラベルに制約(上下左右のマージンを0)を設定
3. ViewControllerの実装
ViewControllerは以下のように実装する。
import UIKit
//各TableViewCellのIdentifier
private let topCellID = "topCellID"
private let middleCellID = "middleCellID"
private let bottomCellID = "bottomCellID"
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var mainTable: UITableView!
static let cellIDs: [String] = [topCellID, middleCellID, bottomCellID]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
mainTable.delegate = self
mainTable.dataSource = self
mainTable.estimatedRowHeight = 5
mainTable.rowHeight = UITableViewAutomaticDimension
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// 行数
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ViewController.cellIDs.count
}
// セル
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellId: String = ViewController.cellIDs[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: cellId)!
if cellId == topCellID {
let label = cell.viewWithTag(100) as! UILabel
label.text = "上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上上"
} else if cellId == middleCellID {
let label = cell.viewWithTag(100) as! UILabel
label.text = "中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中中"
} else if cellId == bottomCellID {
let label = cell.viewWithTag(100) as! UILabel
label.text = "下下下下下下下下下下下下下下下下下下下下下下下下下下下下下下下下下下下下下下下下下下下下下下下下下下下下下下"
}
return cell
}
// セクション数
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
}
ポイントは、viewDidLoadの以下の部分。
mainTable.estimatedRowHeight = 5
mainTable.rowHeight = UITableViewAutomaticDimension
これでセルの高さを自動的に調整してくれるようになる。