gpt4 book ai didi

ios - UICollectionView - 一次一个 Cell 的水平分页

转载 作者:搜寻专家 更新时间:2023-10-30 22:15:02 25 4
gpt4 key购买 nike

我正在尝试使用 collectionView 实现类似轮播的效果。我实现了 UICollectionView 并将其设置为水平 显示单元格。

唯一的问题是如何只允许出现一个单元格并将该单元格置于屏幕中心。

注意:已启用分页。

我找到了这段代码,试过了但遗憾的是没有用

代码引用: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)
}

最佳答案

对于center cell,上面的代码是正确的,也实现了这两个方法:

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)
}

关于ios - UICollectionView - 一次一个 Cell 的水平分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38894834/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com