'UITableView content offset incorrect when opening backgrounded application in horizontal orientation

I am having the same issue as a person in this thread: https://developer.apple.com/forums/thread/47100

My app has a UITableView embedded in a ViewController. When I scroll to the bottom of this table while the iPad is oriented horizontally, and then switch to another application, then switch back, I find myself a few rows above the bottom instead of being at the bottom like I would expect.

I noticed that on reopening the table is where it would be if the device was oriented vertically instead of horizontally. Visually, what I mean is:

Expected (horizontal): 
__________________________________
|5                               |
|6                               |
|7                               |
|8 (bottom)                      |
----------------------------------

Actual (horizontal):
__________________________________
|2                               |
|3                               |
|4                               |
|5                               |
----------------------------------

Actual (vertical):
___________________
|2                |
|3                |
|4                |
|5                |
|6                |
|7                |
|8 (bottom)       |
-------------------

I tried overriding viewWillTransition in the view controller that contains the UITableView, to no avail:

class AViewController {
    @IBOutlet var tableView: UITableView!
// ...
    override func viewWillTransition(to size: CGSize, with tc: UIViewControllerTransitionCoordinator) {
        if UIApplication.shared.applicationState == .background {
            return
        }
        super.viewWillTransition(to: size, with: tc)
    }
// ...
}

That idea came from moving app to background, calls viewDidLayoutSubView and create a lot of warnings with UICollectionView



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source