Reputation: 717
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.
Here is how my viewController looks like.
Here is how collectionView's attribute inspector and size inspector look like.
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
Reputation: 1158
Firstly, You must set collectionView's cell size to none at storyboard.
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