Reputation: 4885
Swift 5, Xcode latest, iOS 13+
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:
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
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