Swift:按屏幕分页不适用于两个列布局集合视图

时间:2017-02-08 04:48:44

标签: ios swift uicollectionview

我有一个带有自定义2列布局的collectionview控制器:

class CVLayout: UICollectionViewFlowLayout {

override init() {
    super.init()
    setupLayout()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    setupLayout()
}

override var itemSize: CGSize {
    set {

    }
    get {
        let numberOfColumns: CGFloat = 2

        let itemWidth = (self.collectionView!.frame.width - (numberOfColumns - 1)) / numberOfColumns
        return CGSize(width: itemWidth, height: itemWidth)
    }
}

func setupLayout() {
    minimumInteritemSpacing = 1
    minimumLineSpacing = 1
    scrollDirection = .horizontal
}

}

在我的控制器中,我设置了

class ViewController: UICollectionViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    collectionView?.isScrollEnabled = true
    collectionView?.isPagingEnabled = true
}

我有7个项目,屏幕上显示6个项目,我希望在下一页看到一个项目,但我看到4个(上一页3个) 我尝试使用部分中的部分和项目,但它没有帮助。我从其他主题中发现的是默认分页应该是屏幕,而不是单元格(在我的例子中是一个列)。我究竟做错了什么?

2 个答案:

答案 0 :(得分:1)

如果我理解你的问题,我认为你本身并没有做错任何事。集合视图的内容大小(部分)由项目大小确定。现在大约是3个项目的宽度(或一页半内容)。我认为您需要覆盖集合视图的内容大小属性以反映整个内容页面(宽度)以实现所需的效果。

override var collectionViewContentSize: CGSize {

    if  let collectionView = collectionView {
        let numberOfItems = collectionView.numberOfItems(inSection: 0)
        let pages = numberOfItems/2
        let size =  CGSize(width: collectionView.frame.width * CGFloat(pages), height: collectionView.frame.height)
        return size
    }

    return CGSize(width: 0, height: 0)
}

请参阅此回答How to expand UICollectionView contentSize when paging enable?。它有点旧,但我认为它正试图解决同样的问题。

答案 1 :(得分:0)

首先,UICollectionViewFlowLayout不支持分页

我认为有两种解决方案

第一

使用UIScrollView只需使用分页选项

即可添加7个项目

第二

使用UICollectionView修改您的UICollectionViewFlowLayout

子类UICollectionViewFlowLayout以支持分页

离)

在Swift3中

class CustomCollectionViewFlowLayout: UICollectionViewFlowLayout {
    override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
        var offsetAdjustment = CGFloat.greatestFiniteMagnitude
        let horizontalOffset = proposedContentOffset.x
        let targetRect = CGRect(x: proposedContentOffset.x, y: 0, width: self.collectionView!.bounds.size.width, height: self.collectionView!.bounds.size.height)
        for layoutAttributes in super.layoutAttributesForElements(in: targetRect)! {
            let itemOffset = layoutAttributes.frame.origin.x
            if abs(itemOffset - horizontalOffset) < abs(offsetAdjustment){
                offsetAdjustment = itemOffset - horizontalOffset
            }
        }
        return CGPoint(x: proposedContentOffset.x + offsetAdjustment, y: proposedContentOffset.y)
    }
}

您可以在UICollectionViewFlowLayout with Paging

中找到更多信息