我正在尝试使用 collectionView 实现类似轮播的效果。我实施了UICollectionView
并将其设置为显示单元格水平地.
唯一的问题是我怎样才能只允许出现一个单元格并将该单元格放在屏幕上居中。
注意:分页已启用。
我找到了这段代码,尝试了一下,但遗憾的是没有用
代码参考:使用 Swift 创建分页 UICollectionView https://stackoverflow.com/questions/31355226/create-a-paging-uicollectionview-with-swift
override func targetContentOffsetForProposedContentOffset(proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
if let cv = self.collectionView {
let cvBounds = cv.bounds
let halfWidth = cvBounds.size.width * 0.5;
let proposedContentOffsetCenterX = proposedContentOffset.x + halfWidth;
if let attributesForVisibleCells = self.layoutAttributesForElementsInRect(cvBounds) {
var candidateAttributes : UICollectionViewLayoutAttributes?
for attributes in attributesForVisibleCells {
// == Skip comparison with non-cell items (headers and footers) == //
if attributes.representedElementCategory != UICollectionElementCategory.Cell {
continue
}
if let candAttrs = candidateAttributes {
let a = attributes.center.x - proposedContentOffsetCenterX
let b = candAttrs.center.x - proposedContentOffsetCenterX
if fabsf(Float(a)) < fabsf(Float(b)) {
candidateAttributes = attributes;
}
}
else { // == First time in the loop == //
candidateAttributes = attributes;
continue;
}
}
return CGPoint(x : candidateAttributes!.center.x - halfWidth, y : proposedContentOffset.y);
}
}
// Fallback
return super.targetContentOffsetForProposedContentOffset(proposedContentOffset)
}
对于中心单元格,上面的代码是正确的,并且还实现了这两个方法:
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
let currentIndex:CGFloat = self.GridCollectionView.contentOffset.x / self.GridCollectionView.frame.size.width
pageControl.currentPage = Int(currentIndex)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSize(width: collectionView.frame.size.width, height: collectionView.frame.size.width+40)
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)