Button index path from UICollectionView

I tried:

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

But NSLog shows that the cell exists, but the indexpath is zero.

+6
source share
4 answers

OK, here it is:

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

This is sometimes the easiest answer. I had the same problem as @Schmidt, but I was disappointed that his answer was to use indexPathForItemAtPoint: as if indexPathForCell: was somehow broken and could not be used for its intended purpose.

Then I tried its solution and still had the same result: the index path returned to zero.

Solution: The viewView collection controller is not connected to the UICollectionView instance in the NIB (on the storyboard). After creating this missing connection, both methods (indexPathForCell: and indexPathForItemAtPoint) worked as expected.

I know that other developers sometimes encounter this problem, so pay attention to this as a reminder: the problem may not be in your code, in fact, but in the Builder interface, as in an unconnected outlet (or just a confused outlet connected with something that no longer exists).

+1
source

Another best way is to subclass UIButton and add the NSIndexPath property to it. When loading a 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; } 
0
source

Swift response version

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

Source: https://habr.com/ru/post/926192/


All Articles