在集合视图单元格中,我有三个按钮,没有单击/选择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);
}
答案 0 :(得分:1)
您可以使用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];
...
}
您还应该更改按钮的目标操作的分配:
[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)];
...
}
但这对我来说似乎很奇怪。
答案 1 :(得分:1)
您可以尝试此操作,自定义您的单元格或使用标记(无论如何)以确保索引路径,然后使用UIResponder传递您的SEL。例如,
@interface UIResponder (PassAction)
- (void)passAction:(NSString *)actionName otherInfo:(NSDictionary *)otherInfo;
@end
你可以在你的牢房中触发,就像这样:
[self passAction:NSStringFromClass([cell class]) userInfo:@{@"Tag":@(cell.tag)}];
在控制器中,实现如下:
- (void) passAction:(NSString *)eventName otherInfo:(NSDictionary *)userInfo{
NSLog(@"success");
}