LoginSignup
11
16

More than 5 years have passed since last update.

UITableViewCellの高さを自動調整する

Last updated at Posted at 2017-02-17

UITableViewCellの高さを自動調整させる方法をメモ。

1. storyboardでViewControllerにTableViewを設置する

スクリーンショット 2017-02-16 13.48.34.png

今回は、TableViewにTableViewCellを3つ配置。各セル内にラベルを置く。

2. セル内のラベルに制約(上下左右のマージンを0)を設定

スクリーンショット 2017-02-17 19.31.10.png

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

これでセルの高さを自動的に調整してくれるようになる。

4. こんな感じ

Screen Shot 2017-02-17 at 19.54.09.png

11
16
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
11
16