Indexpath of the button from UICollectionView

陌路散爱 提交于 2020-01-02 03:11:09

问题


I tried to:

- (IBAction)delete:(UIButton*)sender{
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:(TourGridCell *)[[[sender superview]superview]superview]];
}

But NSLog shows that cell exist, but indexpath is nil.


回答1:


OK, here it is:

- (IBAction)delete:(UIButton *)sender{
    NSIndexPath *indexPath = nil;
    indexPath = [self.collectionView indexPathForItemAtPoint:[self.collectionView convertPoint:sender.center fromView:sender.superview]];
}



回答2:


Sometimes it's the simplest possible answer. I was having exactly the same problem as @Schmidt, but was frustrated to see that his answer was to use indexPathForItemAtPoint:, as though indexPathForCell: was somehow broken and couldn't be used as intended.

Then I tried his solution, and still had the same result: the index path was coming back nil.

Solution: the view controller's collectionView outlet wasn't connected to the UICollectionView instance in the NIB (on the storyboard). After making that missing connection, both methods (indexPathForCell: and indexPathForItemAtPoint) worked as expected.

I know other devs run into this problem sometimes, so take this as a reminder: the problem may not be your code, per se, but rather something in Interface Builder like an unconnected outlet (or just as confusing, an outlet that's connected to something which no longer exists).




回答3:


Swift version of the answer

var indexPath: IndexPath? = nil
indexPath = collectionView.indexPathForItem(at: collectionView.convert(sender.center, from: sender.superview))



回答4:


Another best way is to subclass the UIButton and add an NSIndexPath property to it. When loading the cell in
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath method add this statement. yourCell.customButton.indexPath = indexPath;

And

- (IBAction)delete:(UIButton *)sender  
{
  NSIndexPath *indexPath = sender.indexPath;
}


来源:https://stackoverflow.com/questions/12579911/indexpath-of-the-button-from-uicollectionview

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