Yoel Jimenez del valle
Yoel Jimenez del valle

Reputation: 1278

collection view cell width is not correct

after update to ios 12 and xcode 10 the collectionView with cell sizeing cell does not work correctly anymore.

i have this layout in xcode

enter image description here

the view is like this.

enter image description here

and this is how it looks now.

enter image description here

i have tried to set the collectionview view a widht constraint and modified in the

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
cell.widthConstraint.constant = UIScreen.main.bounds.width / 3

but nothing happens.

Upvotes: 1

Views: 2498

Answers (1)

Yury Imashev
Yury Imashev

Reputation: 2128

You were using the wrong method to set the cells size. Instead of collectionView(_:cellForItemAt:) use collectionView:layout:sizeForItemAtIndexPath:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let itemHeight = 60
    let itemWidth = UIScreen.main.bounds.width / 3
    return CGSize(width: itemWidth, height: itemHeight)
}

Also, you can set up items size using Interface Builders Size Inspector, but in that case, the size of your cells will be absolute. If you want it to be 1/3 of screen width, you need to use the layout delegate.

Upvotes: 1

Related Questions