简体   繁体   中英

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:

普通表视图

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

旋转的异常表视图

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:

在此处输入图片说明

Thanks for the help.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM