Reputation: 5661
I've got a few collectionviewcells being created from an array. What I want is a static cell that sits at the very end of all these cells.
so not matter how many cells I add, this particular cell stays at the very end
Also if its impossible to do this, what ideas do you have to accomplish what I'm trying
Thank you so much. I really appreciate any answers you offer
Upvotes: 2
Views: 3510
Reputation: 4919
yes this is absolutely possible.
In func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int
you should always return 1 more than the number of items you have.
In func collectionView(_ collectionView: UICollectionView,
cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
you should check to see if indexPath.row is equal to the number of items you have. If it is, configure that particular cell to have a + sign.
Common Mistake Below
Be sure that for this last cell you do NOT make a call accessing the same Array you use for tags.
For example, if your array of tags looks like this:
var myItems = ["Tag1", "Tag2", "Tag3"]
Then the following code is erroneous:
var titleToDisplayOnCell = myItems[indexPath.row] // Don't do this!
This is because for the cell where the + sign should be displayed, row is 3 and there is no object at myItems[3] -- that's beyond the bounds of the array, which is 0 to 2 inclusive.
Upvotes: 4
Reputation: 181
Yes, this is definitely possible. My preferred way to accomplish this is to use two separate sections in the collection view:
func numberOfSections() -> Int {
return 2
}
func numberOfItemsInSection(_ section: Int) -> Int {
if section == 0 {
return array.count
} else if section == 1 {
return 1
} else {
return 0
}
}
func cellForItemAtIndexPath(_ indexPath: NSIndexPath) -> UICollectionViewCell? {
if indexPath.section == 0 {
// set up the standard cell, using the data from the army
} else if indexPath.section == 1 {
//set up the "+" cell
}
}
The other way you can achieve this same goal is to just use one section, declare the size of the collection view as being the size of the array + 1, and setting up the extra cell in an if statement in the cellForItemAtIndexPath method, but you will find it will lead to a lot more complications with the extra math. It is usually safer to keep cells using different data in different sections if at all possible
Upvotes: 2