user1662494
user1662494

Reputation: 93

adding one extra item in Collection View controller

I am having one array which is having 10 element. which I am able to set as item in Collection view. Now I want to add 11th element, which will be one button.

How can I do that?

Upvotes: 0

Views: 945

Answers (3)

d512
d512

Reputation: 34263

The way I did this was to make

collectionView:numberOfItemsInSection:

return one more item than I actually had in my array. Then I did a test inside

collectionView:cellForItemAtIndexPath:

to see if indexPath.row == myArray.count. If so, you know it's time to add the special button cell at the end. Otherwise, you're just adding another real cell to the collection view.

- (NSInteger) collectionView:(UICollectionView*)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self->myArray.count + 1;
}

- (UICollectionViewCell*) collectionView:(UICollectionView*)collectionView cellForItemAtIndexPath:(NSIndexPath*)indexPath
{
    if(indexPath.row < self->myArray.count)
    {
        //add regular cell to the list
    }
    else
    {
        //at the end so add special button cell to the list
    }
}

I do not recommend that you simply add a dummy object to your array before rendering the collection view. This was the first method I tried. Making sure it's in the list at the right times and not in the list at the right times is a major pain. Especially if you are persisting that list of objects, it's easy to get into a situation where you accidentally persist the dummy.

Upvotes: 1

Vineet Singh
Vineet Singh

Reputation: 4019

If you are filling your collection view by your array,Then for adding an extra item or new item,just add it in your array through which you are filling your collection view by using that array in method cellForItemAtIndexPath:,So that you would be able to include a new cell in your collectionview.

Upvotes: 0

ragnarok
ragnarok

Reputation: 75

if i understood well, you should:

  1. subclass UICollectionViewCell and add an IBOutlet for the button;
  2. add a new prototype cell, design it, set the class for your custom class and hook up the outlet;
  3. modify cellForItemAtIndexPath: to include your newCell if indexPath.item is 10;

However is reasonable to avoid buttons in UICollectionViews when you can use cells "as" buttons with didSelectItemAtIndexPath: method.

Upvotes: 0

Related Questions