Max
Max

Reputation: 53

How to make 2 cells in row collection view

I'm trying to get 2 images in row like at screenshot.

What result I want

but this is my real result

my real result

here's my extension of ViewController:

extension ViewController : UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return images.count // images is an array of my UIImages`s
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellImage", for: indexPath) as! imageCollectionViewCell
        cell.imageView.image = images[indexPath.item]
        cell.imageView.contentMode = .scaleAspectFill
        cell.imageView.clipsToBounds = true
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let frameCV = collectionView.frame//размер collectionView
        
        let cellWidth = frameCV.width / CGFloat(countOfCells) // countOfCells == 2
        let cellHeight = cellWidth
        
        return CGSize(width: cellWidth, height: cellHeight)

    }
}

Upvotes: 3

Views: 4001

Answers (1)

Jawad Ali
Jawad Ali

Reputation: 14397

You need to add padding

extension ViewController: UICollectionViewDelegateFlowLayout {
    
 

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
    {
        let leftAndRightPaddings: CGFloat = 45.0
        let numberOfItemsPerRow: CGFloat = 2.0
    
        let width = (collectionView.frame.width-leftAndRightPaddings)/numberOfItemsPerRow
        return CGSize(width: width, height: width) // You can change width and height here as pr your requirement
    
    }
}

Upvotes: 8

Related Questions