使用Swift创建一个分页UICollectionView

使用Swift创建一个分页UICollectionView,第1张

使用Swift创建一个分页UICollectionView

所以我想出了办法。

首先创建一个自定义UICollectionViewFlowLayout并添加重写此方法:

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) as? [UICollectionViewLayoutAttributes] { 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)}

然后在实现UICollectionView的类上执行以下 *** 作:

    let collectionViewLayout: CenterCellCollectionViewFlowLayout = CenterCellCollectionViewFlowLayout()    collectionViewLayout.itemSize = CGSizeMake(self.itemSize, self.itemSize)    collectionViewLayout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)    collectionViewLayout.minimumInteritemSpacing = 0    collectionViewLayout.minimumLineSpacing = self.itemSpacing    collectionViewLayout.scrollDirection = UICollectionViewScrollDirection.Horizontal    var collectionView: UICollectionView = UICollectionView(frame: self.collectionContainer.bounds, collectionViewLayout: collectionViewLayout)    collectionView.delegate = self;    collectionView.dataSource = self;    collectionView.backgroundColor = UIColor.redColor()    collectionView.registerClass(LevelsCustomCell.self, forCellWithReuseIdentifier: reuseIdentifier)    collectionView.registerNib(UINib(nibName: reuseIdentifier, bundle: nil), forCellWithReuseIdentifier: reuseIdentifier)    self.collectionContainer.addSubview(collectionView)

就是这样,就像一个魅力。



欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5008091.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-14
下一篇2022-11-14

发表评论

登录后才能评论

评论列表(0条)

    保存