2018-03-28T11:10:23Z||2018-03-28T13:38:07Z


首先设置delegate.

collectionView.delegate = self

然后实现UICollectionViewDelegateFlowLayout:

class MyViewController {
    // 常量
    let CellWidth = CGFloat(116.0)
    let CellHeight = CGFloat(60.0)
  
    var collectionView: UICollectionView!
  
  /* 此处代码省略 */
}

extension MyViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        let CellCount = items.count
        let CellSpacing = CGFloat(1.0)
        let totalCellWidth = CellWidth * CGFloat(CellCount)
        let totalSpacingWidth = CellSpacing * CGFloat(CellCount - 1)
        
        let leftInset = (CollectionViewWidth - CGFloat(totalCellWidth + totalSpacingWidth)) / 2
        let rightInset = leftInset
        
        return UIEdgeInsetsMake(0, leftInset, 0, rightInset)
    }
}

{ true}