LoginSignup
5
8

More than 5 years have passed since last update.

UITableViewCellの高さを可変にする

Last updated at Posted at 2018-12-18

はじめに

AutoLayoutをコードベース書いた時のメモです。
することは以下の3つ。

  1. cellのcontentViewに追加するViewのAutosizingのレイアウト自動変換をオフにする
  2. cellのcontentViewに追加するobject制約は上下左右にする
  3. 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)
}
5
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
8