LoginSignup
1
1

More than 3 years have passed since last update.

GroupedのUITableViewで一番上の余白を消したい(swift)

Last updated at Posted at 2020-10-09

Xcode-12.0 iOS-14.0 Swift-5.3

はじめに

下記の画像のように stylegroupedUITableView で条件によって一番上の余白の表示・非表示を切り替えたいときに試行錯誤したのでやり方をメモ。

余白表示 余白非表示
success_1 success_2

今回は画像のようにヘッダー表示時は余白をなくして、ヘッダー非表示の場合は余白ありにしたかった。。。

だめだったパターン

とりあえずだめだったパターン。。。下記のように isHeaderShowntrue のときにセクション0にヘッダーを設定して高さを設定してみた。

extension TableViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        guard section == 0 else {
            return UITableView.automaticDimension
        }
        return isHeaderShown ? 50 : UITableView.automaticDimension
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        guard section == 0 else {
            return nil
        }
        return isHeaderShown ? HeaderView() : nil
    }
}

結果

failure

初回表示だけいけてるけど2回目以降がおかしい。。。:frowning2:

いけてそうなパターン1

上の方法 + 下記のようにテーブル更新時に tableHeaderView をいじってみました。

tableView.tableHeaderView = isHeaderShown ? UIView() : nil
tableView.reloadData()

結果

success

いけてそう:tada:

いけてそうなパターン2

上の方法でもいけてそうですがそもそも一番上にしかヘッダー設定しないなら sectionHeader に View を設定する必要はないと思い最終的には下記のようにしました。

extension TableViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        guard section == 0 else {
            return UITableView.automaticDimension
        }
        return isHeaderShown ? CGFloat.leastNormalMagnitude : UITableView.automaticDimension
    }
}

// 更新時の処理
tableView.tableHeaderView = isHeaderShown ? HeaderView(frame: .init(origin: .zero, size: .init(width: 0, height: 50))) : nil
tableView.reloadData()

結果はパターン1と同じだったのでたぶんいけてそう:clap:

おわりに

こんなレイアウトにしたくなるのはレアだと思いますがどなたかの参考になれば幸いです。他にいい方法ご存知でしたらぜひ教えて下さい:pray:

今後は UITableView より UICollectionView 使っていった方がいいよって言うのも聞くしもうあんまりテーブルをごちゃごちゃするのはよくないのかもしれない。。。:thinking:

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