2018-03-28T11:13:52Z||2018-03-28T11:13:52Z


class MyViewController {
    // 常量
    let CellIdentifier = "MyViewControllerCell"
    let CellWidth = CGFloat(116.0)
    let CellHeight = CGFloat(60.0)
    // CollectionView 最大长度
    let CollectionViewWidth = CGFloat(400.0)
  
    var collectionView: UICollectionView!
    var items = [String]()
  
    override func viewDidLoad() {
        super.viewDidLoad()
      
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: CellWidth, height: CellHeight)

        collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        collectionView.register(MyViewControllerCell.self, forCellWithReuseIdentifier: CellIdentifier)
        collectionView.backgroundColor = UIColor.white
        collectionView.dataSource = self
        collectionView.delegate = self
        addSubview(collectionView)
    }
}

// MARK: - UICollectionViewDataSource
extension MyViewController: UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView,
                                 numberOfItemsInSection section: Int) -> Int {
        return items.count
    }
    
    func collectionView(_ collectionView: UICollectionView,
                                 cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CellIdentifier,
                                                      for: indexPath) as! MyViewControllerCell
        // 配置 Cell
        return cell
    }
}

// MARK: - UICollectionViewDelegateFlowLayout
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}