xiaolingxiao
xiaolingxiao

Reputation: 4885

Swift make UITableView fill entire viewport of phone

Platform

Swift 5, Xcode latest, iOS 13+

Problem.

I embedded a UITableView into a UIViewController, and made the table view as tall as possible:

    let screenRect = UIScreen.main.bounds
    let screenWidth = screenRect.size.width
    let screenHeight = screenRect.size.height
    

    let width  = self.view.frame.width
    let height = self.view.frame.height
    tableView.center = self.view.center
    tableView.frame.size.width  = width
    tableView.frame.size.height = screenHeight
        //= UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)

The is fine when the UINavigationController view is visible, but when the navigation controller view move away, I see the tableview is offset from the top of the viewport by the height of the navigation controller view. In the image below, the tableview and its cells are white, while the parent UIViewController view is black. We can see the parent controller in here:enter image description here

I have tried to offset the tablview as we can see, but it does not behave as intended.

Note I would like to avoid the storyboard solution if it exists. Everything in code please, because this table view has other behaviors that I may need to contorl.

Upvotes: 0

Views: 215

Answers (1)

rs7
rs7

Reputation: 1630

The key is to use auto-layout if you want your tableView layout to update automatically. To do so pin your tableView to the safeArea as follows:

    tableView.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
    tableView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor),
    tableView.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor),
    tableView.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor),
    tableView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor)
    ])

Upvotes: 1

Related Questions