我似乎不能弄清楚,当我在模拟器中构建应用程序时,我的左/右UIEdgeInsets没有影响。除了这个问题,我希望我的UICollectionView单元格在一行中有3个项目,但我得到的所有单元格都是彼此整齐的,而且它们非常长。我哪里错了?
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: view.frame.width, height: 100)
}发布于 2020-09-16 18:38:04
在代码中,
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: view.frame.width, height: 100) >>>> You are applying parent view width(full width) to item width
}将以下代码添加到sizeForItemAt方法以获得所需的输出
//define constant value as per your requirement and declare this variables globally
let inset: CGFloat = 10 //define as per your requirement
let minimumInteritemSpacing: CGFloat = 10 //define as per your requirement
let cellsPerRow = 3
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let marginsAndInsets = inset * 2 + collectionView.safeAreaInsets.left + collectionView.safeAreaInsets.right + minimumInteritemSpacing * CGFloat(cellsPerRow - 1)
let itemWidth = ((collectionView.bounds.size.width - marginsAndInsets) / CGFloat(cellsPerRow)).rounded(.down)
return .init(width: itemWidth, height: itemWidth)
}发布于 2020-09-16 18:26:19
您可以像这样按行函数显示三个单元格
let spaceBetweenCells: CGFloat = 10
collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: (collectionView.frame.width - 2* spaceBetweenCells)/3, height: 100)
}https://stackoverflow.com/questions/63917624
复制相似问题