Anan
Anan

Reputation: 9

I want the collection view to show 2 columns per row, how do I do that?

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! SkrapCollectionViewCell
    
    cell.myLabel.text = self.items[indexPath.item]

    return cell
}

This is my collection view code where I need to place the code to edit the number of columns. It is 6 now.

Upvotes: -1

Views: 4555

Answers (2)

Rahul Rathore
Rahul Rathore

Reputation: 807

if you are using a collection view from the storyboard then maybe this solution can work for you

class AbcViewController: UIViewController {

@IBOutlet var collectionView: UICollectionView!

override func viewDidLoad() {
    super.viewDidLoad()
    
    coachCollectionView.dataSource = self
    coachCollectionView.collectionViewLayout = AbcViewController.createLayout()

    
}
static func createLayout() -> UICollectionViewCompositionalLayout {
    let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(1)))
    
    
    let group = NSCollectionLayoutGroup.horizontal(layoutSize:
        NSCollectionLayoutSize(
            widthDimension: .fractionalWidth(1),
            heightDimension: .fractionalHeight(2/5)),
        subitem: item,
        count: 2
    )
    
    
    let section = NSCollectionLayoutSection(group: group)
    
    return UICollectionViewCompositionalLayout(section: section)
}}

Upvotes: 0

Ved Sharma
Ved Sharma

Reputation: 769

You need not check the device size because we can use the collectionView width to calculate the width of the cell. Using the cell width you can calculate the height as per your need.

One more thing: You need to use UICollectionViewDelegateFlowLayout & confirm the delegate & implement method below

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
    let padding: CGFloat =  25
    let collectionViewSize = collectionView.frame.size.width - padding
    return CGSize(width: collectionViewSize/2, height: 115)
}

Upvotes: 1

Related Questions