Indexpath of the button from UICollectionView

我的未来我决定 提交于 2019-12-05 05:19:40

OK, here it is:

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

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).

Swift version of the answer

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

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