0
0

UITableViewの行の高さを一部だけ自動にする

Posted at

これまで UITableView の行の高さを固定にしていましたが、一部、行の内容によって可変にしたいところがありました。最初は、行の ContentView を NSLayoutConstraint でどうにか高さを調整できないかと頑張っていましたが、そんなに難しいことは考えなくてよかったので、残しておきます。

tableView(_:heightForRowAt:) で、高さを自動にしたい行に対してのみ UITableView.automaticDimension を設定すればいいよという結論です。

ソースコード

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  switch indexPath.section {
    case 0,1,2: return 36.0
    default: return UITableView.automaticDimension
  }
}

このコードは、UITableView の行の高さを設定するためのデリゲートメソッド tableView(_:heightForRowAt:) を実装しています。このメソッドは、各行の高さを動的に決定するために使用でき、指定された indexPath(セクションと行番号)に応じて、その行の高さを設定できます。

具体的な処理内容

  • indexPath.section の値に応じて高さを決定
  • セクション 012 に対しては 36.0 ポイント固定に設定
  • それ以外のセクションに対しては、UITableView.automaticDimension を使用して自動で高さを計算

UITableView.automaticDimension について

UITableView.automaticDimension は、セル内のコンテンツや Auto Layout に基づいて行の高さを 自動的に計算 してくれます。この設定により、行の高さをコンテンツのサイズに合わせて動的に調整することができます。

automaticDimension | Apple Developer Documentation
https://developer.apple.com/documentation/uikit/uitableview/1614961-automaticdimension

使用例

メモのセクションが、入力した文字の行数に合わせて、広がっています。

example.png

さいごに

UITableView.automaticDimension が、CGFloat なんだと気づいてやってみたらできたってかんじです。

スクリーンショットのアプリは ↓ なので、興味があれば使ってみてください。
給与管理アプリ:
https://apps.apple.com/jp/app/%E7%B5%A6%E4%B8%8E%E7%AE%A1%E7%90%86%E3%82%A2%E3%83%97%E3%83%AA/id1443054271

0
0
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
0
0