我正在尝试使用集合视图制作幻灯片。一切都运行正常但是当我想在用户滚动时让细胞居中时我不知道怎么做,所以我在网上搜索了,我找到了这个惊人的解决方案形式:https://github.com/damienromito/CollectionViewCustom 但是你可以从屏幕截图中看到的问题是,当我删除页眉和页脚边距时,单元格不再成形为中心,在我的设计中,这些边距不应该存在。你能帮我搞清楚吗?谢谢你:
有边距:
没有边距:
这是处理滚动位置的代码:
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let pageWidth = Float(itemWidth + itemSpacing)
let targetXContentOffset = Float(targetContentOffset.pointee.x)
let contentWidth = Float(collectionView!.contentSize.width )
var newPage = Float(self.pageControl.currentPage)
if velocity.x == 0 {
newPage = floor( (targetXContentOffset - Float(pageWidth) / 2) / Float(pageWidth)) + 1.0
} else {
newPage = Float(velocity.x > 0 ? self.pageControl.currentPage + 1 : self.pageControl.currentPage - 1)
if newPage < 0 {
newPage = 0
}
if (newPage > contentWidth / pageWidth) {
newPage = ceil(contentWidth / pageWidth) - 1.0
}
}
self.pageControl.currentPage = Int(newPage)
let point = CGPoint (x: CGFloat(newPage * pageWidth), y: targetContentOffset.pointee.y)
targetContentOffset.pointee = point
}
这是我删除边距的地方:
func setup() {
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
itemWidth = UIScreen.main.bounds.width - collectionMargin * 2.0
layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
layout.itemSize = CGSize(width: itemWidth, height: itemHeight)
//layout.headerReferenceSize = CGSize(width: collectionMargin, height: 0)
//layout.footerReferenceSize = CGSize(width: collectionMargin, height: 0)
collectionView.backgroundColor = .green
layout.minimumLineSpacing = itemSpacing
layout.scrollDirection = .horizontal
collectionView!.collectionViewLayout = layout
collectionView?.decelerationRate = UIScrollViewDecelerationRateFast
}