使用Swift创建分页的UICollectionView

7
我正在尝试创建一个具有分页功能的UICollectionView,每个项目的最大宽度为250个点,我已经成功创建了它,但是我有两个问题:第一个项目的起始位置不正确,会有更多的空间在开始时,当我尝试滑动时,总会有一些东西阻碍我的平稳滑动。

它看起来像这样:

视频链接

这是我的代码:

CenterCellCollectionFlowLayout.swift

class CenterCellCollectionViewFlowLayout: UICollectionViewFlowLayout {

    override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? {

        var attributesToReturn:[UICollectionViewLayoutAttributes] = super.layoutAttributesForElementsInRect(rect) as! [UICollectionViewLayoutAttributes]

        for var i = 0 ; i < attributesToReturn.count ; i++
        {
            var currentLayoutAttributes: UICollectionViewLayoutAttributes = attributesToReturn[i]
            var maximumSpacing: CGFloat = 50
            let origin: CGFloat
            if i - 1 >= 0 {
                let previousLayoutAttributes = attributesToReturn[i - 1]
                origin = previousLayoutAttributes.frame.maxX
            } else {
                origin = 0
            }

            if origin + maximumSpacing + currentLayoutAttributes.frame.size.width < self.collectionViewContentSize().width
            {
                var frame: CGRect = currentLayoutAttributes.frame
                frame.origin.x = origin + maximumSpacing
                currentLayoutAttributes.frame = frame
            }
        }

        return attributesToReturn

    }

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

MainViewController.swift

class MainViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var collectionViewFlowLayout: CenterCellCollectionViewFlowLayout!

    var collectionObjects: NSMutableArray?
    private let reuseIdentifier = "CollectionViewCell"

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        self.collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
    {
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
    {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! UICollectionViewCell
        cell.backgroundColor = UIColor.greenColor()
        // Configure the cell
        return cell
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
        return 10
    }

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets
    {
        return UIEdgeInsetsMake(0, 0, 0, 0)
    }

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
    {
        return CGSizeMake(250, 250)
    }
}

提前致谢

2个回答

16

一个UICollectionView继承自UIScrollView。将isPagingEnabled设置为true,可以实现分页。


你刚刚否定了所有其他答案!对我有用,谢谢。 - Nick
哎呀,伙计,我以为我需要重新做所有的集合视图,但是你救了我的命! - Ivan

13

所以我弄清楚如何做到这一点。

首先创建一个自定义的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)

就是这样了,运行得非常好。


24
当你复制粘贴别人的代码时,至少应该参考一下它的来源:https://randexdev.com/2014/07/uicollectionview/。 - Benjamin
这段代码对我来说比karmadust的那个更好用。 - Casper Zandbergen
运行得非常顺畅! - Rotem
5
我想要给出致谢,但两个网站都无法使用。不管怎样,我只是想帮助人们,而不是窃取别人的代码。 - ytpm
谢谢!对于我的使用情况,布局代码使单元格“捕捉”到中心,这非常好。 - nivbp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接