UICollectionView Horizontal align scroll first cell center alignment not exactly placing center position very first time using Swift

Viewed 1222

My scenario, I am trying to Implement UICollectionView horizontal scrollview first and last cell center alignment based on selection. Here, Very first time CollectionViewCell first cell not showing exact center position. If I didselect once everything working fine. I need to fix very first time app open first cell not showing exact center position.

NOTE: I didn’t added header and footer also I am done my designing using storyboard.

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let text = self.items[indexPath.row]
        let cellWidth = text.size(withAttributes:[.font: UIFont.systemFont(ofSize: 14.0)]).width + 10.0
        return CGSize(width: cellWidth, height: collectionView.bounds.height)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        let inset: CGFloat = collectionView.frame.width * 0.5 - 52 * 0.5
        return UIEdgeInsets(top: 0, left: inset, bottom: 0, right: inset)
    }
1 Answers

You cannot use 52 directly since as the cell width, since the width of each cell is dynamic.

You need to calculate the leftInsets and rightInsets of the collectionView based on the actual width of first and last cell.

You can calculate the width of first and last cell the same way you did in collectionView(_:layout:sizeForItemAt) method using the first and last element of items array, i.e.

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    //Calculate width of first cell
    var firstCellWidth: CGFloat = 52.0
    if let textAtFirstIndex = self.items.first {
        firstCellWidth = textAtFirstIndex.size(withAttributes:[.font: UIFont.systemFont(ofSize: 14.0)]).width + 10.0
    }

    //Calculate width of last cell
    var lastCellWidth: CGFloat = 52.0
    if let textAtLastIndex = self.items.last {
        lastCellWidth = textAtLastIndex.size(withAttributes:[.font: UIFont.systemFont(ofSize: 14.0)]).width + 10.0
    }

    //Calculate leftInset and rightInset
    let leftInset: CGFloat = (collectionView.frame.width * 0.5) - (firstCellWidth * 0.5)
    let rightInset: CGFloat = (collectionView.frame.width * 0.5) - (lastCellWidth * 0.5)

    return UIEdgeInsets(top: 0, left: leftInset, bottom: 0, right: rightInset)
}

Example:

enter image description here

Let me know in case you still face any issues.

Related