簡體   English   中英

如何居中對齊collectionView單元格?

[英]How do I center align my collectionView cells?

在這里嘗試了此解決方案但它似乎僅適用於垂直布局。 我正在嘗試使其適用於水平布局。 就我而言,我總是希望頂部的3個單元格和底部的2個單元格居中對齊。

例: 例

我認為這應該對您有所幫助(我在委托方法中定義了insets,因為collectionview否則只會使我的第一部分居中,而其他部分則保持不變):

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {

        // handling layout
        // which needs to be centered vertically and horizontally
        // also:
        // maximum number of items = 6
        // maximum number of rows = 2
        // maximum number of items in row = 3
        let numberOfItems: CGFloat
        let numberOfRows: CGFloat
        if collectionView.numberOfItems(inSection: section) > Constants.maxNumberOfItemsInRow  {
            numberOfItems = CGFloat(Constants.maxNumberOfItemsInRow)
            numberOfRows = CGFloat(Constants.maxNumberOfRows)
        } else {
            numberOfItems = CGFloat(collectionView.numberOfItems(inSection: section))
            numberOfRows = CGFloat(Constants.minNumberOfRows)
        }


        let totalCellWidth = Constants.itemSize.width * numberOfItems
        let totalSpacingWidth = Constants.minimumInteritemSpacing * numberOfItems
        var leftInset = (collectionView.layer.frame.size.width - CGFloat(totalCellWidth + totalSpacingWidth)) / 2

        let totalCellHeight = Constants.itemSize.height * numberOfRows
        let maximumSectionHeight = (Constants.itemSize.height * CGFloat(Constants.maxNumberOfRows)) + (CGFloat(Constants.maxNumberOfRows + 1) * Constants.minimumLineSpacing)

        if leftInset < 0.0 { leftInset = 0.0 }

        let topInset = (maximumSectionHeight - totalCellHeight) / 2

        let rightInset = leftInset

        return UIEdgeInsets(top: topInset, left: leftInset, bottom: topInset, right: rightInset)
    }

另外,布局是由類定義的:

class CollectionViewFlowLayout: UICollectionViewFlowLayout {

    // MARK: - Constants

    private struct Constants {
        static let minimumInteritemSpacing: CGFloat = 12.5
        static let minimumLineSpacing: CGFloat = 16.5
        static let itemSize = CGSize(width: 64.0, height: 90.0)
    }

    override func prepare() {

        guard let collectionView = collectionView else { return }

        /// Defining flow layout for collectionview presentation
        itemSize = Constants.itemSize

        headerReferenceSize = CGSize(width: collectionView.dc_width, height: 1)
        scrollDirection = .vertical
        minimumInteritemSpacing = Constants.minimumInteritemSpacing
        minimumLineSpacing = Constants.minimumLineSpacing

        super.prepare()
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM