ios - 处理 Collection View Cell 中元素的手势事件

标签 ios objective-c uicollectionview uicollectionviewcell

如何处理 Collection View 单元格内不同元素内发生的手势事件(在我的例子中是点击)?

我正在使用使用自定义单元格构建的 Collection View 。此自定义单元格包含以下元素:

  • 一个 UILabel
  • 一个 UIImageView
  • 一个按钮

如果用户点击 ImageView,那么用户将看到更大版本的图像。如果用户点击按钮,则图像将在数据库中删除。因此,我需要一种方法来 a) 检测 Collection View 中哪个单元格被点击(类似于方法 didDeselectItemAtIndexPath 提供的功能)和 b) 区分可以在单元格中点击的元素。

在点击 UIImageView 的情况下,我试图捕捉点击并识别 Collection View 的 cellForItemAtIndexPath 方法中的以下代码在哪个单元格上完成的操作:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    PostCellView *postCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PostCellView" forIndexPath:indexPath];
    if(!postCell){
        postCell = [[PostCellView alloc]init];
    }

    long row = indexPath.row;
    PostModel *post = [self.newsfeedPosts objectAtIndex:row];
    NSURL *posterUrl = [NSURL URLWithString:post.media[@"poster"]];

    NSURLSessionDataTask *getPosterImage = [[NetworkHelper getInstance].session dataTaskWithURL:posterUrl completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            UIImage *posterImage = [UIImage imageWithData:data];
            postCell.posterImageView.image = posterImage;

//here is where I try to handle the tap event, if it happens on the uiimabeview
            UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(posterTapDetected:)];
            [tapGestureRecognizer setDelegate:self];
            [postCell.posterImageView addGestureRecognizer:tapGestureRecognizer];                               
        });
    }];
    [getPosterImage resume];

    return postCell;
}

最佳答案

假设您的 Collection View 是一个部分,您可以向 UIImageView 添加一个标签来表示 UIImageView 的行以及单元格,例如。

UIImage *posterImage = [UIImage imageWithData:data];
postCell.posterImageView.image = posterImage;
postCell.posterImageView.tag = row; // <-- add tag

然后识别 posterTapDetected: 中的行,例如:

- (void)posterTapDetected:(UITapGestureRecognizer*)gesture {
    NSLog(@"row %d tapped", (int)gesture.view.tag);
}

至于区分单元格内可以点击的不同元素,如果每个元素的手势识别器链接到不同的方法,则识别点击的元素不需要任何必要的额外工作,因为每个不同元素的点击手势将是由每个 View 对应的 UITapGestureRecognizer 操作方法处理。

关于ios - 处理 Collection View Cell 中元素的手势事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28130407/

相关文章:

ios - AFNetworking SessionManager 设置 HTTPHeaderField 导致错误

ios - 如何使用 Dropbox API 重新连接应用程序

ios - 如何更改 URL iOS 中的参数

ios - 从搜索结果表 (UISearchController) 导航到 View (推送)并保持搜索结果就位

ios - 如何获得行数?

swift - 更改 UICollectionViewCell 中的按钮背景

iphone - 我们如何保护 iPhone 中的 blob 数据?

ios - 如何在 Objective-C 中的 UICollectionView 的 didSelectItemAtIndexPath 委托(delegate)上显示 UIProgressView?

ios - 无限滚动的 UICollectionView?

ios - Http Post参数到url不要在objectC Xcode中发送特殊字符 "+"