はじめに
タイトルのまんまなんですけど、わかりにくいので画像を貼っときます。
やっていきます
調節前のコード
SnapKit使ってます笑
import UIKit
import SnapKit
class ViewController: UIViewController {
private let tableView: UITableView = {
let view = UITableView(frame: .zero, style: .insetGrouped)
view.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
return view
}()
private let items = ["アイテム1", "アイテム2", "アイテム3", "アイテム4", "アイテム5"]
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
private func setup() {
tableView.delegate = self
tableView.dataSource = self
view.addSubview(tableView)
tableView.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
// 1つのセクションに表示するセルの数
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
// セクションの数
func numberOfSections(in tableView: UITableView) -> Int {
return items.count
}
// セルの高さ
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
// セルの設定
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
var content = cell.defaultContentConfiguration()
content.prefersSideBySideTextAndSecondaryText = true
content.text = items[indexPath.row]
content.secondaryText = items[indexPath.row]
content.image = UIImage(systemName: "graduationcap.fill")
cell.contentConfiguration = content
return cell
}
}
やりかた
本来ヘッダーとフッターがある場所ですのでどちらかの高さを0にすれば縮めることができます
いい感じ
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return .zero
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
nil
}
0スペース
両方の高さを0にすればスペースをなくすこともできます
でも、これはおかしいです笑
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return .zero
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
nil
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return .zero
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
return nil
}
自分で調整
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 60
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
nil
}
おわり
もうあんまりUITableViewが使われることはないのかな?