AndroAid
AndroAid

Reputation: 77

imageView UITapGestureRecognizer in a UITableViewCell

I'm trying to add a tap gesture on an imageView, inside a tableView cell. The problem is if I put the gesture code in the cellForRow, it doesn't recognise the url, and off course all the images get the url of the last cell. if I put the gesture code in the didSelect, the url always gets null, I think because the gesture is working before the cell gets it data.

the imageView should open a video file, based on its url, that gets it from an XML parser.

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];
}

Upvotes: 0

Views: 835

Answers (1)

Andrei Chevozerov
Andrei Chevozerov

Reputation: 1029

I think it's better to add a button instead of an imageview. The code should look somehow like this:

// 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];

Then in 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];
}

This approach will prevent you from some side effects of using tap recognizers in table cells. And it's easy to understand and correct.

Upvotes: 4

Related Questions