Talha Ahmad Khan Talha Ahmad Khan - 7 months ago 13
Swift Question

How to have different cell size in flowlayout

This is what I am able to make through a tutorial

This is the Screenshot of the app

But I have to make 1st and every 3rd Cell to be full width. How I supposed to do it?

The code is this

class MainViewController: UICollectionViewController
{

// data source
let publishers = Publishers()

private let leftAndRightPaddings: CGFloat = 32.0
private let numberOfItemsPerRow: CGFloat = 2.0
private let heigthAdjustment: CGFloat = 100

// MARK: - View controller life cycle

override func viewDidLoad() {
super.viewDidLoad()

let width = (CGRectGetWidth(collectionView!.frame) - leftAndRightPaddings) / numberOfItemsPerRow
let layout = collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = CGSizeMake(width, heigthAdjustment)
print(width.description)

}

// MARK: - UICollectionViewDataSource

override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}

override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return publishers.numberOfPublishers
}

private struct Storyboard
{
static let CellIdentifier = "PublisherCell"
}

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(Storyboard.CellIdentifier, forIndexPath: indexPath) as UICollectionViewCell

return cell}

}

Answer

You need to implement this func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize method in your UICollectionViewDelegateFlowLayout