The following question was asked in the Oct 13 iPhone Duo group lab: when you unfold iPhone Duo after you’ve scrolled down, does UIKit keep the position or should we re-anchor ourselves? The answer was various scroll views like collection views and text views will handle this for you to keep visible items visible, which also works when resizing the window on iPad.
This is not working for me with a simple UICollectionView. What do I need to do to obtain this behavior?
class ViewController: UIViewController, UICollectionViewDataSource {
override func viewDidLoad() {
super.viewDidLoad()
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: 80, height: 80)
layout.minimumInteritemSpacing = 8
layout.minimumLineSpacing = 8
layout.sectionInsetReference = .fromLayoutMargins
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.backgroundColor = .systemBackground
collectionView.dataSource = self
collectionView.insetsLayoutMarginsFromSafeArea = true
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
view.addSubview(collectionView)
NSLayoutConstraint.activate([
collectionView.topAnchor.constraint(equalTo: view.topAnchor),
collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
5000
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
var content = UIListContentConfiguration.cell()
content.text = String(indexPath.item)
content.textProperties.alignment = .center
cell.contentConfiguration = content
var background = UIBackgroundConfiguration.clear()
background.backgroundColor = .secondarySystemBackground
cell.backgroundConfiguration = background
return cell
}
}
- Run the app on iPhone Duo
- Scroll down to cell 100 on the outer display
- Unfold the device
Expected: It should stay scrolled to item 100
Actual: It scrolled down to item 225 (or more accurately, the content offset did not change, more content was added higher up with the contentSize shrinking due to the expanded width)
In the past I've put so much work into trying to maintain the expected scroll position for orientation changes on iPhone and iPad/Mac Catalyst resize events, it's surprisingly incredibly hard to get working in every scenario, so I am SUPER interested to learn the system can do it for us!