はじめに
AutoLayoutをコードベース書いた時のメモです。
することは以下の3つ。
- cellのcontentViewに追加するViewのAutosizingのレイアウト自動変換をオフにする
- cellのcontentViewに追加するobject制約は上下左右にする
- cellの高さをdelegateでUITableview.automaticDimensionにする
ViewControllerでの記述
まずはUITableViewDelegateメソッドでAutosizingの自動変換オフとcellの制約を決めていく。
ViewController.swift
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "shareCell", for: indexPath) as! ShareTableViewCell
cell.cellHeaderView.backgroundColor = UIColor.red
//ここでAutosizingの自動変換をオフにする
cell.cellHeaderView.translatesAutoresizingMaskIntoConstraints = false
cell.cellHeaderView.topAnchor.constraint(equalTo: cell.contentView.topAnchor).isActive = true
cell.cellHeaderView.rightAnchor.constraint(equalTo: cell.contentView.rightAnchor).isActive = true
cell.cellHeaderView.leftAnchor.constraint(equalTo: cell.contentView.leftAnchor).isActive = true
cell.cellHeaderView.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor).isActive = true
cell.cellHeaderView.heightAnchor.constraint(equalToConstant: 100).isActive = true
return cell
}
cellの高さを可変に設定
ViewController.swift
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
tableView.estimatedRowHeight = 100
//UITableView.automaticDimensionでcellの高さを可変にする
return UITableView.automaticDimension
}
最後に
cellに追加するView達のインスタンスは一応UITableViewCellクラスで行った。
UITableViewCell.swift
override func awakeFromNib() {
super.awakeFromNib()
cell.contentView.addSubView(cellHeaderView)
}