Mike Mike - 3 years ago 162
Swift Question

Do I need to use the numberOfItemsInSection function if setting the number of items in storyboard?

There are a few posts on

UICollectionViews
and as a general concept I understand
UICollectionViews
are similar to how
TableViews
are implemented. There are a few posts on this topic already.

How to make a simple collection view with Swift

I'm using a
UICollectionView
to layout 8 cells for essentially decorative purposes...just as a container to hold a few images for a page. The images aren't meant to be interactive eg. a shopping cart.

My question is whether I need to implement the function below (and other similar functions) if i'm laying out my cells on the storyboard.

// tell the collection view how many cells to make
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.items.count
}


I have 8 cells within a
UICollectionView
that i have configured on the storyboard (this collection view is a view on a
UIViewController
) and each
UICollectionViewCell
has an image view with in. I have laid this all out on the storyboard.

I also don't want to put an image in each cell. Just a certain number of cels eg. cells 2,3,5 and 8.

So what I was going to do is create a class that extends
UIControllerViewCell
and create an
IBOutlet
for the image view and then in the interface builder reference the custom cell class.

And I think - but could do with some advice - then all I need to do is use the function below and because I only want to populate certain cells I can use an if statement for index path when it's 2,3,5 and 8:

// make a cell for each cell index path
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

if(indexPath == 2 || 3 || 5|| 8)
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell

// Use the outlet in our custom class to get a reference to the UILabel in the cell
cell.image = self.items[indexPath.item]


return cell
}
}


Thanks.

Answer Source

cellForItemAt must return value (which is UICollectionViewCell instance in this case), but you are free to set image of certain cells to nil (AKA no image)

eg:

// make a cell for each cell index path
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! MyCollectionViewCell

    if([2,3,5,8].contains(indexPath.row))
    {
        // Use the outlet in our custom class to get a reference to the UIImageView in the cell
        cell.myImageView.image = self.items[indexPath.row]
    } else {
        cell.myImageView.image = nil
    }

    return cell
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download