ios - 如何在单击按钮时获取并传递 UICollectionViewCell

标签 ios uicollectionview uicollectionviewcell

在一个 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/

相关文章:

ios - 在 iOS 中获取捕获图像中每种颜色的强度

ios - 如何使用 Swift 在 UICollectionViewCell 中设置 UIButton 的标题

ios - UICollectionView 水平滚动

swift - 如何保存从 UIPickerController 中选取的多张图像?

objective-c - 返回整数作为节中项目数时出错

Swift 如何取消选择 Collection Cell

iphone - UISearchDisplayController 搜索结果 TableView 未隐藏在 iOS 7 中

ios - 播放列表(嵌入式)在 iOS 上损坏

ios - 如何创建带参数的枚举?

ios - 使用委托(delegate)将数据从 Collection View Controller 传递到 View Controller