0

我正在尝试在imageView, 内添加点击手势tableView cell。问题是,如果我将手势代码放在 中cellForRow,它无法识别 url,当然所有图像都会获取最后一个单元格的 url。如果我将手势代码放在 中didSelect,则 url 总是为空,我认为是因为手势在单元格获取数据之前就起作用了。

imageView 应该根据其 url 打开一个视频文件,该文件从 XML 解析器获取它。

selectedArticle = [self getArticleAtIndex:indexPath];
UIImageView* imageTap = [          
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]
                                                 initWithTarget:self
                                                 action:@selector(actionHandleTapOnImageView)];
            [singleTap setNumberOfTapsRequired:1];
            imageTap.userInteractionEnabled = YES;
            [imageTap addGestureRecognizer:singleTap]

(void)actionHandleTapOnImageView{
    NSString *path = selectedArticle.videoUrl;
    NSURL *videoURL = [NSURL URLWithString:path];
    MPMoviePlayerViewController *theArticle = [[MPMoviePlayerViewController alloc] initWithContentURL:videoURL];
    [self presentMoviePlayerViewControllerAnimated:theArticle];
    theArticle.moviePlayer.movieSourceType = MPMovieSourceTypeFile;
    [theArticle.moviePlayer play];
}
4

1 回答 1

4

我认为添加按钮而不是图像视图会更好。代码应该看起来像这样:

// in cell for row:
UIButton *buttonImage = [UIButton buttonWithType:UIButtonTypeCustom];
buttonImage.frame = CGRectMake(5.0, 5.0, 40.0, 40.0);
buttonImage.tag = indexPath.row;
[buttonImage setBackgroundImage:yourImage forState:UIControlStateNormal];
[buttonImage addTarget:self action:@selector(imageTap:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:buttonImage];

然后在imageTap

- (void)imageTap:(UIButton *)sender
{
    selectedArticle = [self getArticleAtIndex:sender.tag];
    NSString *path = selectedArticle.videoUrl;
    NSURL *videoURL = [NSURL URLWithString:path];
    MPMoviePlayerViewController *theArticle = [[MPMoviePlayerViewController alloc] initWithContentURL:videoURL];
    [self presentMoviePlayerViewControllerAnimated:theArticle];
    theArticle.moviePlayer.movieSourceType = MPMovieSourceTypeFile;
    [theArticle.moviePlayer play];
}

这种方法将防止您在表格单元格中使用点击识别器的一些副作用。而且很容易理解和纠正。

于 2013-05-26T10:42:58.473 回答