Search code examples
iosswiftuitableviewuikit

Remove top padding from UITableView


I have a UITableView as a cell of another UITableView (nested UITableViews). There is a top padding that I can't reason for, the top padding only appears when I make the CustomTableCell has a UITableView.

class CustomTableCell: UITableViewCell, UITableViewDelegate, UITableViewDataSource {

  private let cellId = "cellId"

  lazy var tableView: UITableView = {

    let tv = UITableView(frame: .zero, style: .grouped)
    tv.translatesAutoresizingMaskIntoConstraints = false
    tv.backgroundColor = .green
    tv.delegate = self
    tv.dataSource = self
    tv.alwaysBounceVertical = false
    tv.isScrollEnabled = false

    tv.separatorColor = .red;
    tv.separatorStyle = .none;

    tv.register(InnerTableCell.self, forCellReuseIdentifier: self.cellId)
    return tv
  }()

  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 10
  }

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

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! InnerTableCell
    return cell
  }

  func setupAutoLayout() {

    tableView.leftAnchor.constraint(equalTo: contentView.leftAnchor).isActive = true
    tableView.rightAnchor.constraint(equalTo: contentView.rightAnchor).isActive = true
    tableView.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
    tableView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
  }

  override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)

    contentView.backgroundColor = .white
    contentView.addSubview(tableView)
    setupAutoLayout()
  }

  required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
}

Here is the link to entire code: https://ideone.com/QAxkPR

Here is how it looks in reveal enter image description here


Solution

  • Change style to .plain instead of .grouped

    let tv = UITableView(frame: .zero, style: .plain)