Joshua
Joshua

Reputation: 503

How to: Center UICollectionViewCells

I have a collection view data source that is going through a view updates / and has its data reloaded multiple times in the process. Can someone show me how to center the cells after everything is done?

data source method:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.testSlice.count
    }

current method handling styling the cells and doing a few other things:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell

        cell.profilePicture.layer.masksToBounds = true

        print("DEV: testSlice value: \(testSlice)")
        print("DEV: limitedNames value: \(limitedNames)")

        if testSlice != [] {
            cell.profilePicture.playPortalProfilePic(forImageId: testSlice[indexPath.item], { error in
                if let error = error {
                    print("Error requesting profile pic: \(String(describing: error))")

                    if let index = self.testSlice.index(of: "") {
                        self.testSlice.remove(at: index)
                        collectionView.reloadData()


                    }

                }
            }
            )
        } else {
            print("items array was empty, value: \(items)")
        }



        cell.backgroundColor = UIColor.cyan
        cell.layer.borderColor = UIColor.black.cgColor
        cell.layer.borderWidth = 1
        cell.layer.cornerRadius = 8

        return cell
    }

I believe I am looking for someone who is great with constraints unless this can be done some other way.

I am trying to center the cells under the label shown

I am trying to center the cells under the label shown

Upvotes: 2

Views: 111

Answers (1)

Razi Tiwana
Razi Tiwana

Reputation: 1435

You can center the cells by adjusting the inset for the section (if you only have one section)

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

    let widthOfCell = 50 // What ever the width of the cell is 
    let spacingBetweenCells = 10 

    let totalCellWidth = widthOfCell * self.data.count
    let totalSpacingWidth = spacingBetweenCells * (self.data.count - 1)

    let leftInset = (collectionView.frame.width - CGFloat(totalCellWidth + totalSpacingWidth)) / 2

    if leftInset < 0 {
        return UIEdgeInsets.zero
    }

    let rightInset = leftInset

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

Upvotes: 1

Related Questions