Проблемы с производительностью с UITableViewCell GestureReognizer - PullRequest
1 голос
/ 13 марта 2012

Я добавил устройства распознавания жестов с одним или двумя касаниями в UITableViewCells. Но после прокрутки таблицы несколько раз становится все более длительная пауза между окончанием моего жеста прокрутки для прокрутки таблицы и началом анимации прокрутки.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"tableViewCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }

    UITapGestureRecognizer* singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
    singleTap.numberOfTapsRequired = 1;
    singleTap.numberOfTouchesRequired = 1;
    [cell addGestureRecognizer:singleTap];

    UITapGestureRecognizer* doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTap:)];
    doubleTap.numberOfTapsRequired = 2;
    doubleTap.numberOfTouchesRequired = 1;
    [singleTap requireGestureRecognizerToFail:doubleTap];
    [cell addGestureRecognizer:doubleTap];

    if (tableView == self.searchDisplayController.searchResultsTableView) {
        // search results
    }
    else {
        // normal table
    }

    return cell;
}

SingleTap: и doubleTap: методы

- (void)singleTap:(UITapGestureRecognizer *)tap
{
    if (UIGestureRecognizerStateEnded == tap.state) {
        UITableViewCell *cell = (UITableViewCell *)tap.view;
        UITableView *tableView = (UITableView *)cell.superview;
        NSIndexPath* indexPath = [tableView indexPathForCell:cell];
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
        // do single tap
    }
}

- (void)doubleTap:(UITapGestureRecognizer *)tap
{
    if (UIGestureRecognizerStateEnded == tap.state) {
        UITableViewCell *cell = (UITableViewCell *)tap.view;
        UITableView *tableView = (UITableView *)cell.superview;
        NSIndexPath* indexPath = [tableView indexPathForCell:cell];
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
        // do double tap
    }
}

Поскольку начальная прокрутка плавная, я попытался добавить распознаватели жестов в условие if (cell == nil), но затем они никогда не добавлялись в ячейки.

У меня также изначально были добавлены жесты в tableView, а не в отдельные ячейки, но это вызвало проблемы с searchDisplayController, т.е. нажатие на кнопку отмены не распознано.

Я бы оценил любые мысли, спасибо.

1 Ответ

6 голосов
/ 13 марта 2012

Метод cellForRowAtIndexPath вызывается несколько раз для одного и того же NSIndexPath, поэтому в ячейки добавляется слишком много распознавателей жестов. Таким образом, производительность пострадает.

Моим первым предложением было бы добавить только один распознаватель жестов в табличное представление. (Я написал этот ответ на похожий вопрос: https://stackoverflow.com/a/4604667/550177)

Но, как вы сказали, это вызывает проблемы с searchDisplayController. Может быть, вы можете избежать их с помощью интеллектуальной реализации UIGestureRecognizerDelegate (верните NO в -(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer;, когда касание произошло не в ячейке).

Мое второе предложение: добавлять распознаватели жестов только один раз:

if ([cell.gestureRecognizers count] == 0) {
    // add recognizer for single tap + double tap
}
...