在一个 Collection View 单元格中,我有三个按钮并且没有单击/选择 UICollectionViewCell
,我如何才能获得被单击按钮的索引路径?
到目前为止,这是我的代码:
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
UIButton * button = (UIButton *)[cell viewWithTag:10];
UILabel * labelTitle = (UILabel *)[cell viewWithTag:20];
UIButton * shareBtn = (UIButton *)[cell viewWithTag:30];
UIButton * editBtn = (UIButton *)[cell viewWithTag:40];
[shareBtn addTarget:self action:@selector(shareDoc:) forControlEvents:UIControlEventTouchUpInside];
[editBtn addTarget:self action:@selector(editDoc) forControlEvents:UIControlEventTouchUpInside];
return cell;
}
-(void)shareDoc:(UICollectionViewCell *) senderCell
{
UICollectionView * collectionView = [self.view viewWithTag:22];
UICollectionViewCell * cCell = [self.view viewWithTag:11];
NSIndexPath * indexPath = [collectionView indexPathForCell:cCell];
NSLog(@"cell: %ld", indexPath.row); //But this just returns 0 every time I clicked on a button.
NSLog(@"section: %ld", indexPath.section);
}
最佳答案
您可以使用 indexPathForItemAtPoint:
并使用将事件作为参数的操作方法。像这样:
- (IBAction)shareDoc:(id)inSender forEvent:(UIEvent * )inEvent {
UITouch *theTouch = inEvent.allTouches.anyObject;
CGPoint thePoint = [theTouch locationInView:self.collectionView];
IndexPath *theIndexPath = [self.collectionView indexPathForItemAtPoint:thePoint];
...
}
您还应该更改按钮的 Target-Action 的分配:
[shareBtn addTarget:self action:@selector(shareDoc:forEvent:) forControlEvents:UIControlEventTouchUpInside];
由于these answers ,你应该添加contentOffset
,如果滚动后索引路径错误:
- (IBAction)shareDoc:(id)inSender forEvent:(UIEvent * )inEvent {
UITouch *theTouch = inEvent.allTouches.anyObject;
CGPoint theOffset = self.collectionView.contentOffset
CGPoint thePoint = [theTouch locationInView:self.collectionView];
IndexPath *theIndexPath = [self.collectionView indexPathForItemAtPoint:CGPointMake(thePoint.x + theOffset.x, thePoint.y + theOffset.y)];
...
}
但这对我来说似乎很奇怪。
关于ios - 如何在单击按钮时获取并传递 UICollectionViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48314237/