具有居中单元格的UICollectionViewFlowLayout

时间:2017-08-18 11:55:00

标签: ios swift uicollectionview uicollectionviewflowlayout

我正在尝试使用居中的单元格实现水平对齐CollectionView,并且我正在使用自定义UICollectionViewFlowLayout。我找到了几个UICollectionViewDelegateFlowLayout的解决方案,但如果您使用自定义UICollectionViewFlowLayout,则不会调用该委托。

这是我的UICollectionViewFlowLayout。任何想法该怎么做?

class MyFlowLayout: UICollectionViewFlowLayout {

    var numberOfRows = 1
    var cellPadding: CGFloat = 15.0

    var availableSize = CGSize.zero
    fileprivate var cache = [UICollectionViewLayoutAttributes]()
    fileprivate var contentWidth: CGFloat  = 0.0
    fileprivate var contentHeight: CGFloat {

        var collectionViewHeight = collectionView!.bounds.height
        if availableSize.height > 0{
            collectionViewHeight = availableSize.height
        }

        let insets = collectionView!.contentInset
        return collectionViewHeight - (insets.top + insets.bottom)
    }

    func reInit(_ newSize: CGSize){

        availableSize = newSize
        cache.removeAll()
    }


    override func prepare() {

        if cache.isEmpty {

            let rowHeight = contentHeight / CGFloat(numberOfRows)

            var yOffset = [CGFloat]()
            for row in 0 ..< numberOfRows {
                yOffset.append(CGFloat(row) * rowHeight )
            }
            var row = 0
            var xOffset = [CGFloat](repeating: 0, count: numberOfRows)


            for item in 0 ..< collectionView!.numberOfItems(inSection: 0) {

                let indexPath = IndexPath(item: item, section: 0)

                let height =  rowHeight
                let width = CGFloat(height / 1.27)

                let frame = CGRect(x: xOffset[row], y: yOffset[row], width: width, height: height)
                let insetFrame = frame.insetBy(dx: cellPadding * 2, dy: cellPadding)

                let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
                attributes.frame = insetFrame
                cache.append(attributes)

                contentWidth = max(contentWidth, frame.maxX)
                xOffset[row] = xOffset[row] + width

                row = row >= (numberOfRows - 1) ? 0 : (row + 1)
            }
        }
    }


    override var collectionViewContentSize : CGSize {

        return CGSize(width: contentWidth, height: contentHeight)
    }

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {

        var layoutAttributes = [UICollectionViewLayoutAttributes]()

        for attributes in cache {
            if attributes.frame.intersects(rect) {
                layoutAttributes.append(attributes)
            }
        }
        return layoutAttributes
    }
}

布局以这种方式连接:

collectionView.collectionViewLayout = MyFlowLayout()
collectionView.register(MyCell.self, forCellWithReuseIdentifier: MyCell.identifier)
collectionView.dataSource = self

调用MyFlowLayout中的准备。

0 个答案:

没有答案