EverythingEnds
EverythingEnds

Reputation: 77

Resizing tableView with Rotation of Device

I am trying to make a tableView that fills my screen. And on launch, whether the table is horizontal or vertical, it always looks good:

Normal table View

But once you rotate the device, the tableView reveals the screen behind it:

Abnormal Table View with Rotation

I first tried using a recommendation from SO of this code snippet:

tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | 
                             UIViewAutoresizingFlexibleHeight

But I got the errors: use of unresolved identifier: UIViewAutoresizingFlexibleHeight use of unresolved identifier: UIViewAutoresizingFlexibleHeight

So I tried to reload the frame on rotation with:

didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation)

But that didn't seem to work either. Note that the view loads nicely in either landscape or portrait, but it goes awry once the view is flipped.

Here is the code I am currently rolling with in viewDidLoad:

  super.viewDidLoad()
    tableView = UITableView(frame: view.bounds, style: .plain)
    tableView.backgroundColor = UIColor.blue

    let cellNib = UINib(nibName: "PostTableViewCell", bundle: nil)
    tableView.register(cellNib, forCellReuseIdentifier: "postCell")
    view.addSubview(tableView)
    tableView.register(LoadingCell.self, forCellReuseIdentifier: "loadingCell")
    var layoutGuide:UILayoutGuide!

    layoutGuide = view.safeAreaLayoutGuide

    tableView.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor).isActive = true
    tableView.topAnchor.constraint(equalTo: layoutGuide.topAnchor).isActive = true
    tableView.bottomAnchor.constraint(equalTo: layoutGuide.bottomAnchor).isActive = true
    tableView.trailingAnchor.constraint(equalTo: layoutGuide.leadingAnchor).isActive = true
    tableView.estimatedRowHeight = UITableViewAutomaticDimension
    tableView.frame = self.view.bounds
    tableView.delegate = self
    tableView.dataSource = self
    tableView.tableFooterView = UIView()
    tableView.reloadData()

Here's a pic of my story board for reference:

enter image description here

Thanks for the help.

Upvotes: 0

Views: 286

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

You only need

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

And comment

tableView.frame = self.view.bounds

Upvotes: 1

Related Questions