嘿,我有一个带有以下滚动行为的集合视图:
单元格之间需要间隔16磅,滚动时保持居中。您只能在演示中看到第一个和最后一个单元格保持居中。我的集合视图宽度与屏幕的宽度相同。在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)
}
重要的是,下一个单元格的一部分显示在屏幕上,当前单元格居中(如演示中的第一个和最后一个单元格)。我该如何实现这种行为?
答案 0 :(得分:0)
您可以在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)
}
不要忘记实施以下协议
UICollectionViewDelegateFlowLayout