Question: Description:
------------

Answer for `Objective-C` and `Swift2.0`: [How to center align the cells of a UICollectionView?](https://stackoverflow.com/questions/13588283/how-to-center-align-the-cells-of-a-uicollectionview) 

I usually would try to convert the `Swift2.0` answer to the `Swift3.0` solution, however the method:

```
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
        let edgeInsets = (screenWight - (CGFloat(elements.count) * 50) - (CGFloat(elements.count) * 10)) / 2
        return UIEdgeInsetsMake(0, edgeInsets, 0, 0);
    }

```

doesn't seem to exist in `Swift3.0`,and the only other method I found that seems useful is:

```
func collectionView(_ collectionView: UICollectionView, transitionLayoutForOldLayout fromLayout: UICollectionViewLayout, newLayout toLayout: UICollectionViewLayout) -> UICollectionViewTransitionLayout {
        <#code#>
}

```

but I am unsure how to implement it correctly.

Question:
---------

How to center align the cells of a `UICollectionView` in `Swift3.0`?

(A simple and general solution for iOS and tvOS would be perfect)

Answer: 
Slight adaptation of @rottenoats answer. This is more generic. 

Most importantly remember to make your view controller conform to the UICollectionViewDelegateFlowLayout protocol.

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

    guard let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout else {
        return .zero
    }

    let cellCount = CGFloat(collectionView.numberOfItems(inSection: section))

    if cellCount > 0 {
        let cellWidth = flowLayout.itemSize.width + flowLayout.minimumInteritemSpacing

        let totalCellWidth = cellWidth * cellCount
        let contentWidth = collectionView.frame.size.width - collectionView.contentInset.left - collectionView.contentInset.right - flowLayout.headerReferenceSize.width - flowLayout.footerReferenceSize.width

        if (totalCellWidth < contentWidth) {
            let padding = (contentWidth - totalCellWidth + flowLayout.minimumInteritemSpacing) / 2.0
            return UIEdgeInsetsMake(0, padding, 0, 0)
        }
    }

    return .zero
}

```
Assuming that you are conforming to [UICollectionViewDelegateFlowLayout](https://developer.apple.com/reference/uikit/uicollectionviewdelegateflowlayout), it should be:

```
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    let edgeInsets = (screenWight - (CGFloat(elements.count) * 50) - (CGFloat(elements.count) * 10)) / 2
    return UIEdgeInsets(top: 0, left: edgeInsets, bottom: 0, right: 0)
}

```