ShedSports
ShedSports

Reputation: 739

2 Cells in UICollectionView row

I am trying to have 2 collectionView cells per row in my CollectionView, I want them to both be half of the width of the collectionView, but when doing that it only displays 1 cell per row, this is the code I have to size it:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: self.collectionView.frame.width / 2, height: 190)
    }

I'm not sure why this shouldn't work, can anyone help out?

When I subtract some width it displays 2 per row, but then the cells' width are smaller than half of the screen size

Upvotes: 0

Views: 896

Answers (3)

Virani Vivek
Virani Vivek

Reputation: 896

Sometime you must use both via collectionViewDelegateFlowLayout and second like below:

func setupCollectionView() {
    let layout = UICollectionViewFlowLayout()
    layout.sectionInset = .zero
    layout.minimumLineSpacing = 0 //as per your requirement
    layout.minimumInteritemSpacing = 0 //as per your requirement
    layout.scrollDirection = .vertical
    layout.itemSize = CGSize(width: self.yourCollectionView.frame.width / 2, height: 190)
    self.yourCollectionView.collectionViewLayout = layout
}

Upvotes: 0

mahan
mahan

Reputation: 14935

You need to set minimumLineSpacing to 0

layout.minimumLineSpacing = 0 

Or

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 0.0
}

Upvotes: 1

ShedSports
ShedSports

Reputation: 739

Had to set spacing to 0 in the UICollectionView attribute inspector

Upvotes: 0

Related Questions