Buttons on a UICollectionViewCell

寵の児 提交于 2019-12-11 08:18:02

问题


One of the new ios6 classes is uicollectionview 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.


回答1:


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;
}


来源:https://stackoverflow.com/questions/12608896/buttons-on-a-uicollectionviewcell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!