Search code examples
swiftuitableviewscreen-rotation

Table View layout not updating on device orientation change


So I have created a tableView and have made it's frame identical to the view's frame, so therefore it should be the same size of the phone screen. However when I change the device orientation to landscape in the simulator the table view keeps the same dimensions from portrait mode.

Here is my tableView code:

        func setTableView() {
    tableView.translatesAutoresizingMaskIntoConstraints = false
    tableView.frame = view.frame
    tableView.backgroundColor = UIColor.lightGray
    tableView.delegate = self
    tableView.dataSource = self
    tableView.separatorColor = UIColor.lightGray

    tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}

Here is the viewDidLoad method:

       override func viewDidLoad() {
    super.viewDidLoad()
    view.addSubview(tableView)
    setTableView()

}

Here is the method where I detect orientation change:

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)


    if UIDevice.current.orientation.isLandscape {


        print("Landscape")

    } else {



        print("Portrait")

    }
}

Here is what I get in the simulator. In landscape mode the table view is only half of the width of the view while it should always fill the whole screen.

enter image description here

enter image description here


Solution

  • Usually if you want the frame of a view to determine its anchors, you don't set tableView.translatesAutoresizingMaskIntoConstraints = false. Setting that flag to false will force it to rely on anchors as opposed to its own view frame to set its constraints.

    You could try setting it to true, or you could try just constraining the table to the view like so:

    self.view.addSubview(tableView)
    tableView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
    tableView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
    tableView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
    tableView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
    

    This will constrain it to the view frame. If you do it this way, you don't need to worry about setting tableView.frame = view.frame. Personally, I prefer this method over relying on view's frames.