首页 > 解决方案 > UICollectionView 不适合某些 Apple 设备上的视图控制器

问题描述

我做了一个UICollectionView,它在大多数类型的 iPhone 上都能正常显示。但是,在 iPhone SE 等较小的设备上,即使我正确设置了约束,集合视图单元也会超出页面。我收到以下错误:

the behavior of the UICollectionViewFlowLayout is not defined because:
the item width must be less than the width of the UICollectionView minus
the section insets left and right values, minus the content insets left and right values.

我尝试了人们提到的许多其他解决方案,例如self.collectionView.collectionViewLayout.invalidateLayout()或设置contentInsetAdjustmentBehavior.never链接此处),但到目前为止,它们都没有奏效,并且对于较小的 iOS 设备,集合视图仍然在页面之外运行。任何帮助将不胜感激。

标签: swiftuicollectionview

解决方案


可能的解决方案:(将此代码放在 ViewDidLoad() 函数中)

let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 20, left: 0, bottom: 10, right: 0) //set section inset as per your requirement.
layout.itemSize = CGSize(width: screenWidth/3, height: screenWidth/3) //set cell item size here 
layout.minimumInteritemSpacing = 0 //set Minimum spacing between 2 items
layout.minimumLineSpacing = 0  //set minimum vertical line spacing here between two lines in collectionview
collectionView!.collectionViewLayout = layout 

推荐阅读