我正在尝试将收集单元格设置在屏幕中央,但没有得到想要的结果。
1。我想要的结果
2。当前输出
我尝试了下面的代码,但是没有用。
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize.init(width: 80, height: 80)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
let totalCellWidth = 80 * 3
let totalSpacingWidth = 10 * (3 - 1)
let leftInset = (collectionView.frame.size.width - CGFloat(totalCellWidth + totalSpacingWidth)) / 2
let rightInset = leftInset
return UIEdgeInsetsMake(0, leftInset, 0, rightInset)
}
已更新以下内容,以便更好地理解。
对于6个项目,它应该看起来像这样
|x x x|
|x x x|
对于5个项目,它应该看起来像这样
|x x x|
| x x |
对于4个项目,它应该看起来像这样
|x x x|
| x |
答案 0 :(得分:0)
尝试以下代码:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
let cellWidth : CGFloat = 80 * 3
let numberOfCells = floor(self.view.frame.size.width / cellWidth)
let edgeInsets = (self.view.frame.size.width - (numberOfCells * cellWidth)) / (numberOfCells + 1)
return UIEdgeInsetsMake(15, edgeInsets, 0, edgeInsets)
}