alphonse
alphonse

Reputation: 717

how to set each collectionview cell size in one collectionview using storyboard and swfit?

I have one collectionView in a viewController, and in this collectionView I have two collectionView Cells and each one has it's own cell identifier and size.

What I'm going to do , when user taps CardView button then collectionView will display cell items with Identifier "CardCell" size of 300x400.

And If user taps ListView, it will display cell items with identifier "ListCell" size of 300x100.

Currently I'm detecting which cell to show, I created enum and variable cellIndex.

enum CellIndexType: Int {
    case cardView
    case listView
}
var cellIndex = 0

and If cellIndex equals to 0, vc will display "CardCell" and if 1, will display "ListCell".

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    var cell = Cell()

    if cellIndex == CellIndexType.cardView.rawValue {
        if let reusableCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CardCell", for: indexPath) as? Cell {
            cell = reusableCell
        }
    } else {
        if let reusableCell = collectionView.dequeueReusableCell(withReuseIdentifier: "ListCardCell", for: indexPath) as? Cell {
            cell = reusableCell
        }
    }
    return cell
}

Here is my viewController with two cells in one CollectionView.

enter image description here

Here is how my viewController looks like.

enter image description here

Here is how collectionView's attribute inspector and size inspector look like.

enter image description here enter image description here

But with my configurations in storyboard and code, it always displays cells size of 300x400.

In which way can I implement this logic?

Upvotes: 0

Views: 2184

Answers (1)

Picode
Picode

Reputation: 1158

Firstly, You must set collectionView's cell size to none at storyboard.

enter image description here

Secondly, use collectionView's sizeForItemAt func :

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    if self.cellIndex == 0{
        return CGSize(width: 300, height: 400)
    } else if self.cellIndex == 1{
        return CGSize(width: 300, height: 100)
    }
}

In addition, register your cells at viewDidLoad:

yourCollectionView.delegate = self
yourCollectionView.dataSource = self
yourCollectionView.register(UINib(nibName: "CardCell", bundle: nil), forCellWithReuseIdentifier: "CardCell")
yourCollectionView.register(UINib(nibName: "ListCell", bundle: nil), forCellWithReuseIdentifier: "ListCell")
yourCollectionView.reloadData()

Hope it helps...

Upvotes: 4

Related Questions