For UICollectionViews
, is it possible to have multiple cell types?
For example:
media_cell
regular_cell
ad_cell
Would you just have to register them or do you have to include an if statement and change the layout according to some variable to achieve this effect.
For example:
if cell.ad == true {
}
The reason being, I want a slightly different sized cell for when an image is present. I guess resizing the cell could work but I haven't seen anything on this online.
Any suggestions
Alternatively, you can drag more than one cell from the Object Library into your collection view, assign a subclass and reuse identifier for the cell and design it as needed. Just like you would for a single cell.
You need to implement a custom UICollectionViewLayout. With a horizontal flow layout it's going to fill from top to bottom first, then move to the right. Since you have two rows, as specified in sizeForItemAt, section 0 will fill from top to bottom, then right to left, and so will section 1.
Use a cell registration to register cells with your collection view and configure each cell for display. You create a cell registration with your cell type and data item type as the registration's generic parameters, passing in a registration handler to configure the cell.
There are no section headers in the UICollectionView. So for your first task, you'll add a new section header using the search text as the section title. To display this section header, you'll use UICollectionReusableView .
Try this: 1. Register two(or more) cells. 2.Configure cellforItem for each. 3. Configure sizeForItem for each. First:
self.collectionView.register(SmallCell.self, forCellWithReuseIdentifier: "smallCell")
self.collectionView.register(BigCell.self, forCellWithReuseIdentifier: "bigCell")
And then:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if dataSource[indexPath.item].hasImage {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: “smallCell”, for: indexPath) as! SmallCell
let model = dataSource[indexPath.item]
cell.model = model
return cell
} else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: “bigCell”, for: indexPath) as! BigCell
let model = dataSource[indexPath.item]
cell.model = model
return cell
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if dataSource[indexPath.item].hasImage {
return CGSize(width: collectionView.frame.width, height: cellHeight+100)
} else {
return CGSize(width: collectionView.frame.width, height: cellHeight)
}
}
Two things and everything should be works:
Great tutorial
More info in this brilliant answer here
Good luck :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With