UICollectionView自定义水平分页布局

[![collectionview example] [1]] [1]

我正在尝试使用集合视图模拟此行为。 我已经开始使用这种方法,并使我更接近。 虽然当我在水平分页CollectionView上进一步向右滑动时,内容会进一步向左移动。 单元之间的间隔也是closures的。 我相信它需要一个自定义的布局,但我不确定。

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return CGSize(width: collectionView.frame.width - 20, height: collectionView.frame.height - 20) } 

它取决于3个因素1)部分插图2)单元间距3)单元尺寸

任何改变,你必须改变他人的情况

1)左右设置20

在这里输入图像说明

2)将单元格间距设置为10

 func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat { return 10 } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat { return 10 } 

3)设置单元格大小

 func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return CGSize(width: collectionView.frame.width / 1.15 ,height: collectionView.frame.height) } 

4)这将在屏幕中心单元格

 func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { let pageWidth:CGFloat = scrollView.frame.width / 1.15 + cellSpacing ; let currentOffset:CGFloat = scrollView.contentOffset.x; let targetOffset:CGFloat = targetContentOffset.memory.x var newTargetOffset:CGFloat = 0; if targetOffset > currentOffset { newTargetOffset = ceil(currentOffset / pageWidth) * pageWidth; } else { newTargetOffset = floor(currentOffset / pageWidth) * pageWidth; } if newTargetOffset < 0 { newTargetOffset = 0 } else if newTargetOffset > scrollView.contentSize.width { newTargetOffset = scrollView.contentSize.width; } targetContentOffset.memory.x = currentOffset scrollView.setContentOffset(CGPointMake(newTargetOffset, 0), animated: true) }