Catch uiimageviewe touch in uitableviewcell

2019-09-09 22:32发布

问题:

I have following code that does not work: I never get to goToFoodDetail.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"<#MyCell#>";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
    }

    NSInteger objectLocation = indexPath.row;

    UILabel* lblText = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 260, 20)];
    [lblText setFont:[UIFont fontWithName:@"Helvetica" size:10.0]];
    [lblText setText:[food foodName]];
    [cell addSubview:lblText];

    UILabel* lblType = [[UILabel alloc] initWithFrame:CGRectMake(0, 21, 260, 20)];
    [lblType setFont:[UIFont fontWithName:@"Helvetica" size:9.0]];
    lblType.textColor = [UIColor blueColor  ];
    [lblType setText:[food foodType]];
    [cell addSubview:lblType];

    UIImageView * detailImage = [[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"paris.jpg"]] autorelease];
    detailImage.frame = CGRectMake(270, 4, 40, 36);   
    cell.imageView.userInteractionEnabled = YES;
    cell.imageView.tag = indexPath.row;

    UITapGestureRecognizer *tapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(goToFoodDetail:)];
    tapped.numberOfTapsRequired = 1;
    [cell.imageView addGestureRecognizer:tapped];   
    [tapped release];

    [cell addSubview:detailImage];
    [detailImage release];
    [lblText release];
    [lblType release];
    return cell;
}

-(void)goToFoodDetail :(id) sender
{
    UITapGestureRecognizer *gesture = (UITapGestureRecognizer *) sender;
    NSLog(@"Tag = %d", gesture.view.tag);
}

回答1:

It looks like you're creating a new UIImageView that shows the image Paris.jp and adding that to your cell, but then adding a tap gesture recognizer to the cell's default image view, but not setting it's image. Are you intending to have two image views in each cell, or just one?

If you intend to have the cell's image view both show the image and be tappable, then you don't need to create the other image view. You can just set cell.imageView.image = [UIImage imageWithName:"Paris.jog"] and attach the gesture recognizer to the same.