Search code examples
objective-cios6uicollectionview

Buttons on a UICollectionViewCell


One of the new classes is which allows one to display items in a grid format similar to the Homescreen / iBooks / Pages layout.

Is there was a way to receive a touch event on a button that is on the UICollectionViewCell? Currently, my cell is created through an XIB file and added to the UICollectionView programatically. I'm looking for something similar to the Detail Diclosure Indicator on a UITableView.

After looking through Apple's documentation here, I don't see any methods that allow for something like that, but I am positive there's a way to do it.

How can one add a button to a UICollectionViewCell and get the indexPath of the cell when the button is tapped?

Are there any tutorials or links out there that could be helpful? iOS 6 is fairly new so I haven't found much. Thanks in advance.


Solution

  • One way is to add an NSIndexPath property to your cell and set it when the cell is dequeued. Then, your cell's action handler would have access to the current index.

    Snippet for your UICollectionViewCell:

    @interface MyCustomCell : UICollectionViewCell
    @property (weak, nonatomic) NSIndexPath *indexPath;
    - (IBAction)testClicked:(id)sender; // TODO: wire up your button to this handler
    @end
    

    Snippet for your view controller implementing UICollectionViewDataSource:

    -(UICollectionViewCell*) collectionView:(UICollectionView *)collectionView
                     cellForItemAtIndexPath:(NSIndexPath *)indexPath
    {
        MyCustomCell *cell = 
            [collectionView dequeueReusableCellWithReuseIdentifier:@"myCustomCell"
                                                      forIndexPath:indexPath];
        cell.indexPath = indexPath;
        // TODO: other initialization for the cell
        return cell;
    }