如何在与导航栏标题的前沿相同的集合视图单元格中配置间距?
Posted
技术标签:
【中文标题】如何在与导航栏标题的前沿相同的集合视图单元格中配置间距?【英文标题】:How to configure spacing in a collection view cell that is the same as the leading edge with the navigation bar title? 【发布时间】:2020-04-25 22:52:43 【问题描述】:我有一个 UICollectionViewController,我想在其中显示左边缘与导航栏标题对齐的集合视图单元格。由于设备屏幕尺寸不同,我当然不想硬编码 CGFloat 20 的间距。从我下面的代码中可以看出,在 iPhone 8+ 和 iPhone 11 Pro Max 上的实现看起来不错,但在 iPhone 11 上却不行(集合视图单元格的左边缘比导航栏标题的边缘更靠右,如图所示我的代码下方的图像)。
有谁知道以编程方式(或通过情节提要)对齐导航栏标题和集合视图单元格的前沿的方法?
private let reuseIdentifier = "Cell"
class CollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout
private let spacing: CGFloat = 20 // CGFloat of 20 works well for the iPhone 8+ and iPhone 11 Pro Max, but not the iPhone 11 Pro
override func viewDidLoad()
super.viewDidLoad()
// Register cell classes
self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
// Setup layout
let layout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: spacing, left: spacing, bottom: spacing, right: spacing)
layout.minimumLineSpacing = spacing
layout.minimumInteritemSpacing = spacing
self.collectionView?.collectionViewLayout = layout
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int
return 1
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
return 16
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
cell.backgroundColor = .systemFill
return cell
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
let numberOfItemsPerRow: CGFloat = 2
let spacingBetweenCells: CGFloat = spacing
let totalSpacing = (2 * self.spacing) + ((numberOfItemsPerRow - 1) * spacingBetweenCells) // Amount of total spacing in a row
if let collection = self.collectionView
let width = (collection.bounds.width - totalSpacing) / numberOfItemsPerRow
return CGSize(width: width, height: width)
else
return CGSize(width: 0, height: 0)
【问题讨论】:
【参考方案1】:我想到了一个巧妙的解决方案。也许是一种解决方法,但我很满意。
// Change private let spacing: CGFloat = 20 to
private var spacing = CGFloat()
// Upon loading, spacing will be initialized depending on screen width
override func viewDidLoad()
super.viewDidLoad()
// Added code
if UIScreen.main.bounds.width <= 375
spacing = 16 // For the iPhone 7, 8, 11 Pro
else
spacing = 20 // For the iPhone 7+, 8+ and 11 Pro Max
【讨论】:
以上是关于如何在与导航栏标题的前沿相同的集合视图单元格中配置间距?的主要内容,如果未能解决你的问题,请参考以下文章