问题描述
我现在正在为图片制作一个 collectionView,我想让它像下面这样。
然而,当我向右/向左滚动时,下一个项目永远不会在中心,我尝试了很多方法仍然无法解决问题。 有人可以帮我吗?
下面是代码。
func collectionView(_ collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,insetForSectionAt section: Int) -> UIEdgeInsets {
let cellCount = CGFloat(Config.banners.count)
if cellCount > 0 {
let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
let cellWidth = screenSize.width - flowLayout.minimumInteritemSpacing
flowLayout.itemSize = CGSize(width: cellWidth,height: 250)
flowLayout.minimumLinespacing = -60
let totalCellWidth = cellWidth*cellCount
let totalSpacingWidth = 30 * (cellCount - 1)
let contentWidth = collectionView.frame.size.width
if (totalCellWidth < contentWidth) {
print("totalCellWidth < contentWidth")
let padding = (contentWidth - totalCellWidth) / 2.0
return UIEdgeInsets(top: 0,left: padding,bottom: 0,right: padding)
} else {
print("totalCellWidth > contentWidth")
return UIEdgeInsets(top: 0,left: 10,right: 0)
}
}
return UIEdgeInsets.zero
}
解决方法
在您的代码中添加这些行 collectionviewflowdelegate 方法。它会起作用。我通过添加这些方法实现了同样的目的。
func collectionView(_ collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = UIScreen.main.bounds.width / 3.0
let height = collectionView.frame.size.height
return CGSize(width: width,height: height)
}
func collectionView(_ collectionView: UICollectionView,minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0.0
}
func collectionView(_ collectionView: UICollectionView,minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0.0
}