How to center align the cells of a UICollectionView?

前端 未结 18 2490
梦如初夏
梦如初夏 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 01:59

    Working version of kgaidis's Objective C answer using Swift 3.0:

    let flow = UICollectionViewFlowLayout()
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {        
        let numberOfItems = collectionView.numberOfItems(inSection: 0)
        let combinedItemWidth:CGFloat = (CGFloat(numberOfItems) * flow.itemSize.width) + ((CGFloat(numberOfItems) - 1) * flow.minimumInteritemSpacing)
        let padding = (collectionView.frame.size.width - combinedItemWidth) / 2
    
        return UIEdgeInsetsMake(0, padding, 0, padding)
    }
    

提交回复
热议问题