How to center align the cells of a UICollectionView?

前端 未结 18 2496
梦如初夏
梦如初夏 2020-11-28 01:33

I am currently using UICollectionView for the user interface grid, and it works fine. However, I\'d like to be enable horizontal scrolling. The grid supports 8

18条回答
  •  甜味超标
    2020-11-28 02:11

    Here is how you can do it and it works fine

    func refreshCollectionView(_ count: Int) {
        let collectionViewHeight = collectionView.bounds.height
        let collectionViewWidth = collectionView.bounds.width
        let numberOfItemsThatCanInCollectionView = Int(collectionViewWidth / collectionViewHeight)
        if numberOfItemsThatCanInCollectionView > count {
            let totalCellWidth = collectionViewHeight * CGFloat(count)
            let totalSpacingWidth: CGFloat = CGFloat(count) * (CGFloat(count) - 1)
            // leftInset, rightInset are the global variables which I am passing to the below function
            leftInset = (collectionViewWidth - CGFloat(totalCellWidth + totalSpacingWidth)) / 2;
            rightInset = -leftInset
        } else {
            leftInset = 0.0
            rightInset = -collectionViewHeight
        }
        collectionView.reloadData()
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsetsMake(0, leftInset, 0, rightInset)
    }
    

提交回复
热议问题