注意:以下答案基于问题所有者和我自己之间的讨论。
您需要正确设置collectionViewFlowLayout 以实现所需的输出。试试下面的代码:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
// All the values are changable according to your needs.
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.sectionInset = UIEdgeInsets.zero
layout.minimumInteritemSpacing = 1
layout.minimumLineSpacing = 2
return CGSize(width: (self.collectionView.frame.width / 2) - 1 , height:(self.collectionView.frame.height / 3) - 1)
}
更新1:计算布局包括navigationBar和StatusBar。
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
// All the values are changable according to your needs.
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.sectionInset = UIEdgeInsets.zero
layout.minimumInteritemSpacing = 1
layout.minimumLineSpacing = 2
return CGSize(width: (self.collectionView.frame.width / 2) - 1 , height:(((self.view.frame.height - ((navigationController?.navigationBar.frame.height)! + UIApplication.shared.statusBarFrame.height)) / 3) - 1))
}
您可能需要验证 viewDidLayoutSubviews 或 viewWillLayoutSubviews 中的 collectionView 框架
override func viewDidLayoutSubviews() {
collectionView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height)
}
以下链接可以帮助您了解collectionViewFlowLayout。
Enforce collectionView to have only 2 rows
uicollectionview remove top padding
Adjust cellsize for fit all screens?
注意:以后,请用相关代码发布您的问题并清楚地说明问题。