
在viewDidLoad中设置如下所示:
func setupCollectionView() {
collectionView.delegate = self
collectionView.dataSource = self
collectionView.showsHorizontalScrollIndicator = false
collectionView.showsVerticalScrollIndicator = false
collectionView.register(UINib(nibName: "SubtopicCollectionCell", bundle: nil), forCellWithReuseIdentifier: "SubtopicCollectionCell")
let flowLayout = UICollectionViewFlowLayout()
flowLayout.scrollDirection = .horizontal
flowLayout.minimumLineSpacing = 16
collectionView.isPagingEnabled = true
collectionView.setCollectionViewLayout(flowLayout, animated: false)
}不同的委托方法如下:
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: SubtopicCollectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: "SubtopicCollectionCell", for: indexPath) as! SubtopicCollectionCell
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.size.width * 0.78, height: collectionView.frame.size.height)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 0, left: 40, bottom: 0, right: 40)
}重要的是,下一个单元格的一部分以当前单元格为中心显示在屏幕上(就像演示中的第一个和最后一个单元格一样)。如何实现此行为?
发布于 2017-09-28 19:31:21
您可以在collectionViewLayout函数中通过以下简单计算来实现。
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
let cellWidth = CellWidth * CellCount
let spacingWidth = CellSpacing * (CellCount - 1)
let leftInset = (collectionViewWidth - CGFloat(CellWidth + SpacingWidth)) / 2
let rightInset = leftInset
return UIEdgeInsetsMake(0, leftInset, 0, rightInset)
}别忘了实现以下协议
UICollectionViewDelegateFlowLayouthttps://stackoverflow.com/questions/46467693
复制相似问题