UITapGestureRecognizer в UIImageView в UITablevlewCell не вызывается

В настоящее время у меня есть пользовательский UITableViewCell, который содержит UIImageView и безуспешно пытается добавить UITapGestureRecognizer в UIImageView. вот фрагмент кода.

//within cellForRowAtIndexPath (where customer table cell with imageview is created and reused)
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleImageTap:)];
tap.cancelsTouchesInView = YES;
tap.numberOfTapsRequired = 1;
tap.delegate = self;
[imageView addGestureRecognizer:tap];
[tap release];

// handle method
- (void) handleImageTap:(UIGestureRecognizer *)gestureRecognizer {
    RKLogDebug(@"imaged tab");
}

Я также установил userInteractionEnabled в ячейке и супервизор UIImageView, но все равно не повезло, есть подсказки?

ИЗМЕНИТЬ:

Я также удалил выделение ячейки с помощью cell.selectionStyle = UITableViewCellSelectionStyleNone; Может ли это быть проблемой


person Herman    schedule 12.10.2011    source источник
comment
во-первых, почему вы не используете UIButton вместо представления изображения? Во-вторых, вы включили взаимодействие с пользователем для фактического просмотра изображения?   -  person Rog    schedule 12.10.2011
comment
@Rog, потому что я хочу использовать функцию UIViewContentModeScaleAspectFit UIImageView, имеет ли UIButton ту же функциональность?   -  person Herman    schedule 12.10.2011
comment
Также при использовании UIControl в режиме прокрутки он блокирует прокрутку, когда начинается касание...   -  person JakubKnejzlik    schedule 14.10.2012
comment
Каково имя переменной UIImageView?   -  person Ray Shih    schedule 09.01.2013
comment
Я бы убедился, что все родительские представления достаточно велики для отображения дополнительных представлений. Жесты «достигают» дочерних представлений только в том случае, если сенсорная область «поражает» всю цепочку родительских и дочерних представлений.   -  person G Man    schedule 16.11.2016


Ответы (3)


Взаимодействие с пользователем UIImageView отключено по умолчанию. Чтобы он реагировал на прикосновения, его необходимо явно включить.

imageView.userInteractionEnabled = YES;
person EmptyStack    schedule 12.10.2011
comment
Может быть, у вас есть UIView над ним? - person Thomas Decaux; 23.05.2013
comment
Спасибо! У меня тоже сработало =) - person CodeMonkey; 11.12.2014
comment
Хороший. Это помогает мне. - person Thuan Nguyen; 23.07.2020

Свифт 3

Это сработало для меня:

self.isUserInteractionEnabled = true
person ƒernando Valle    schedule 08.02.2017

В моем случае это выглядит так:

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellIdentifier = CELL_ROUTE_IDENTIFIER;
    RouteTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    if (cell == nil) {
        cell = [[RouteTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                         reuseIdentifier:cellIdentifier];
    }

    if ([self.routes count] > 0) {
        Route *route = [self.routes objectAtIndex:indexPath.row];

        UITapGestureRecognizer *singleTapOwner = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                    action:@selector(imageOwnerTapped:)];
        singleTapOwner.numberOfTapsRequired = 1;
        singleTapOwner.cancelsTouchesInView = YES;
        [cell.ownerImageView setUserInteractionEnabled:YES];
        [cell.ownerImageView addGestureRecognizer:singleTapOwner];
    } else {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    return cell;
}

И селектор:

- (void)imageOwnerTapped:(UISwipeGestureRecognizer *)gesture {
    CGPoint location = [gesture locationInView:self.tableView];
    NSIndexPath *tapedIndexPath = [self.tableView indexPathForRowAtPoint:location];
    UITableViewCell *tapedCell  = [self.tableView cellForRowAtIndexPath:tapedIndexPath];

    NSIndexPath *indexPath = [self.tableView indexPathForCell:tapedCell];
    NSUInteger index = [indexPath row];

    Route *route = [self.routes objectAtIndex:index];
}
person levo4ka    schedule 20.07.2015