怠慢プログラマーの備忘録

怠慢でナマケモノなプログラマーの備忘録です。

【Swift】TableViewのcell数以外のGridを非表示にする(完全備忘録)

※完全備忘録です。

TableView.cellの数が2担っている状態でもデフォルトではそれ以上のGridが表示されてしまう。

// MARK: - UITableViewDataSource
extension MenuViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }    
}

f:id:ka0in:20180114171041p:plain

numberOfRowsInSectionで指定した数以外のcellおよびgridを非表示にしたい。

手順1: XIBでstyleをGroupedに変更

そうするとconstraintを指定しても上部に空白ができる。

f:id:ka0in:20180114171543p:plain

手順2:heightForHeaderInSectionを追加

下記のコードをUITableViewDelegateに追加する

// MARK: - UITableViewDelegate
extension MenuViewController: UITableViewDelegate {       
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return .leastNormalMagnitude
    }
}

すると、、、 f:id:ka0in:20180114171807p:plain

とできます。

以上