Search code examples
iosswiftautolayout

Why did I get empty cells in UITableView?


I put my UITableView in UIScrollView > View > StackView.

And I implemented table view in View Controller as usual with numberOfRowsInSection and cellForRowAt. Here's my extension.

extension OrderViewController: UITableViewDataSource, UITableViewDelegate {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    print("DEBUG: orderItems.count - \(orderItems.count)")
    return orderItems.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: OrderCell.id, for: indexPath) as! OrderCell
    cell.configure(orderItems[indexPath.row])
    return cell
} 

}

But my simulator actually shows empty cells. I already checked the orderItems array only has 2 members.

I guess it is because either auto layout or stack view. In the stack view, I gave height constraints for every views except table view since it has to have dynamic cell number.

I don't know what I have to change.

my simulator with two array items

hierarchy of table view (no anchor of height) table view's attribute


Solution

  • This is because your tableview has full height with related your view. Just add on viewDidLoad

    yourTableView.tableFooterView = UIView()
    

    But if you want dynamic height for your tableview then do that;

    1. Give a height constraint for your tableview
    2. Create an IBOutlet for this constraint

    After you reload your tableview

    heightConstraint.constant = yourRowHeight * arrayCount
    self.view.layoutIfNeeded()