I have a collection view and I want some cells to display even if there is a small amount of data. For example, in this picture, notice how there is only 1 item but all the other cells are still showing with a background color.
I know how to do this only by faking the amount of data used to populate the collection view in numberOfItemsInSection
. This is my sample code:
class ViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
let itemArray = ["1"]
}
extension ViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
/// Note I can fake more cells here but don't think this is correct way.
return itemArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! FavoritesCollectionViewCell
return cell
}
}
This only needs to work until there is enough cells to display in a screen. For example, there needs to be about 8 cells to fill the screen, once there are enough items in the array to fit the screen, this is no longer necessary.
Any thoughts?
Update 1:
This collection view will support adding ,deleting, and sorting the items. Not sure if this will this be a problem if I add fake data in numberOfItemsInSection