LoginSignup
16
19

More than 5 years have passed since last update.

【Swift】TableViewでセルの高さを変更しよう

Last updated at Posted at 2019-06-11

1. セルの高さを一定の値に固定したい場合

tableview.rowHeight = 高さ とする。

もしくはUITableViewDelegateを継承している場合、以下の書き方でもセルの高さを固定させることができる。

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 高さ
    }

2. セルの高さを可変にしたい場合

tableView.estimatedRowHeight = 高さ
tableView.rowHeight = UITableViewAutomaticDimension の2つを追記する

まとめ


class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    @IBOutlet var commentTableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        commentTableView.delegate = self
        commentTableView.dataSource = self

        let nib = UINib(nibName: "CommentTableViewCell", bundle: Bundle.main)
        commentTableView.register(nib, forCellReuseIdentifier: "cell")

        //1. 固定にしたいとき
        commentTableView.rowHeight = 100

        //2. 可変にしたいとき
        commentTableView.estimatedRowHeight = 66
        commentTableView.rowHeight = UITableViewAutomaticDimension

    }

   //1. UITableViewDelegateを継承している場合
   func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }
}
16
19
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
16
19