Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionView in landscape on iPhone X

When iPhone X is used landscape, you're supposed to check safeAreaInsets to make suitably large gutters on the left and right. UITableView has the new insetsContentViewsToSafeArea property (default true) to automatically keep cell contents in the safe area.

I'm surprised that UICollectionView seems to not have anything similar. I'd expect that for a vertically-scrolling collection view, the left and right sides would be inset to the safe area when in landscape (and conversely, a horizontally-scrolling collection view would be inset if needed in portrait).

The simplest way to ensure this behaviour seems to be to add to the collection view controller:

- (void)viewSafeAreaInsetsDidChange {     [super viewSafeAreaInsetsDidChange];     UIEdgeInsets contentInset = self.collectionView.contentInset;     contentInset.left = self.view.safeAreaInsets.left;     contentInset.right = self.view.safeAreaInsets.right;     self.collectionView.contentInset = contentInset; } 

... assuming contentInset.left/right are normally zero.

(NOTE: yes, for a UICollectionViewController, that needs to be self.view.safeAreaInsets; at the time this is called, the change to safeAreaInsets has oddly not yet propagated to self.collectionView)

Am I missing something? That boilerplate is simple enough, but it's effectively necessary now for every collection view that touches a screen edge. It seems really odd that Apple didn't provide something to enable this by default.

like image 487
Wes Campaigne Avatar asked Sep 16 '17 21:09

Wes Campaigne


People also ask

What is UICollectionView flow layout?

A layout object that organizes items into a grid with optional header and footer views for each section.

How does UICollectionView work?

From apple's documentation, UICollectionView is: An object that manages an ordered collection of data items and presents them using customizable layouts. The name and definition makes it clear, it is a way to display a Collection of UI Views in our app. The individual view is referred as a Cell.

How does swift implement UICollectionView?

Select the Main storyboard from the file browser. Add a CollectionView by pressing command shift L to open the storyboard widget window. Drag the collectionView onto the main view controller. Add constraints to the UICollectionView widget to ensure that the widget fills the screen on all devices.


1 Answers

Having the same issue. This worked for me:

override func viewDidLoad() {     if #available(iOS 11.0, *) {         collectionView?.contentInsetAdjustmentBehavior = .always     } } 

The documentation for the .always enum case says:

Always include the safe area insets in the content adjustment.

This solution works correctly also in the case the phone is rotated.

like image 87
petrsyn Avatar answered Sep 23 '22 08:09

petrsyn