私がしようとしました:
- (IBAction)delete:(UIButton*)sender{
NSIndexPath *indexPath = [self.collectionView indexPathForCell:(TourGridCell *)[[[sender superview]superview]superview]];
}
しかし、NSLogはセルが存在することを示していますが、indexpathはnilです。
私がしようとしました:
- (IBAction)delete:(UIButton*)sender{
NSIndexPath *indexPath = [self.collectionView indexPathForCell:(TourGridCell *)[[[sender superview]superview]superview]];
}
しかし、NSLogはセルが存在することを示していますが、indexpathはnilです。
OK、ここにあります:
- (IBAction)delete:(UIButton *)sender{
NSIndexPath *indexPath = nil;
indexPath = [self.collectionView indexPathForItemAtPoint:[self.collectionView convertPoint:sender.center fromView:sender.superview]];
}
時にはそれが最も簡単な答えです。私は@Schmidtとまったく同じ問題を抱えていましたが、彼の答えがindexPathForItemAtPoint:を使用することであることに不満を感じていました。まるで、indexPathForCell:が壊れていて、意図したとおりに使用できなかったかのようです。
それから私は彼の解決策を試しましたが、それでも同じ結果が得られました。インデックスパスはnilに戻っていました。
解決策:ビューコントローラーのcollectionViewアウトレットが、(ストーリーボード上の)NIBのUICollectionViewインスタンスに接続されていませんでした。欠落している接続を確立した後、両方のメソッド(indexPathForCell:およびindexPathForItemAtPoint)は期待どおりに機能しました。
他の開発者が時々この問題に遭遇することを知っているので、これを思い出してください:問題はそれ自体があなたのコードではなく、接続されていないアウトレット(または同じように紛らわしい、何かに接続されているアウトレット)のようなInterfaceBuilderの何かである可能性がありますもはや存在しません)。
答えの迅速なバージョン
var indexPath: IndexPath? = nil
indexPath = collectionView.indexPathForItem(at: collectionView.convert(sender.center, from: sender.superview))
もう1つの最良の方法は、UIButtonをサブクラス化し、それにNSIndexPathプロパティを追加することです。メソッドにセルをロードするときに、
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
このステートメントを追加します。
yourCell.customButton.indexPath = indexPath;
と
- (IBAction)delete:(UIButton *)sender
{
NSIndexPath *indexPath = sender.indexPath;
}