Как я могу обнаружить двойное нажатие на определенную ячейку в UITableView? - PullRequest
34 голосов
/ 23 июня 2009

Как я могу обнаружить двойное нажатие на определенную ячейку в UITableView?

т.е. Я хочу выполнить одно действие, если пользователь сделал одно касание, и другое, если пользователь сделал двойное касание? Мне также нужно знать индексный путь, где было сделано касание.

Как мне достичь этой цели?

Спасибо.

Ответы [ 14 ]

0 голосов
/ 02 ноября 2017

Это решение работает только для UICollectionView или ячейки UITableView.

Сначала объявите эти переменные

int number_of_clicks;

BOOL thread_started;

Затем поместите этот код в didDelectItemAtIndexPath

++number_of_clicks;
if (!thread_started) {

    thread_started = YES;

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
                                 0.25 * NSEC_PER_SEC),
                   dispatch_get_main_queue(),^{

                       if (number_of_clicks == 1) {
                           ATLog(@"ONE");
                       }else if(number_of_clicks == 2){
                           ATLog(@"DOUBLE");
                       }

                       number_of_clicks = 0;
                       thread_started = NO;

                   });

        }

0,25 - задержка в 2 клика. Я думаю, что 0,25 идеально подходит для обнаружения этого типа клика. Теперь вы можете обнаружить только один клик и два клика по отдельности. Удачи

0 голосов
/ 29 апреля 2014

Улучшение для oxigen ответ.

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    if(touch.tapCount == 2) {
        CGPoint touchPoint = [touch locationInView:self];
        NSIndexPath *touchIndex = [self indexPathForRowAtPoint:touchPoint];
        if (touchIndex) {
            // Call some callback function and pass 'touchIndex'.
        }
    }
    [super touchesEnded:touches withEvent:event];
}
0 голосов
/ 13 марта 2014

Вот мое полное решение:

CustomTableView.h

//
//  CustomTableView.h
//

#import <UIKit/UIKit.h>

@interface CustomTableView : UITableView

    // Nothing needed here

@end

CustomTableView.m

//
//  CustomTableView.m
//

#import "CustomTableView.h"

@implementation CustomTableView


//
// Touch event ended
//
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{

    // For each event received
    for (UITouch * touch in touches) {

        NSIndexPath * indexPath = [self indexPathForRowAtPoint: [touch locationInView:self] ];

        // One tap happened
        if([touch tapCount] == 1)
        {
            // Call the single tap method after a delay
            [self performSelector: @selector(singleTapReceived:)
                       withObject: indexPath
                       afterDelay: 0.3];
        }


        // Two taps happened
        else if ([touch tapCount] == 2)
        {
            // Cancel the delayed call to the single tap method
            [NSObject cancelPreviousPerformRequestsWithTarget: self
                                                     selector: @selector(singleTapReceived:)
                                                       object: indexPath ];

            // Call the double tap method instead
            [self performSelector: @selector(doubleTapReceived:)
                       withObject: indexPath ];
        }


    }

    // Pass the event to super
    [super touchesEnded: touches
              withEvent: event];

}


//
// Single Tap
//
-(void) singleTapReceived:(NSIndexPath *) indexPath
{
    NSLog(@"singleTapReceived - row: %ld",(long)indexPath.row);
}


//
// Double Tap
//
-(void) doubleTapReceived:(NSIndexPath *) indexPath
{
    NSLog(@"doubleTapReceived - row: %ld",(long)indexPath.row);
}



@end
0 голосов
/ 29 апреля 2013

Примечание: пожалуйста, смотрите комментарии ниже, чтобы увидеть, хотя, хотя это решение работало для меня, оно все еще не может быть хорошей идеей.

Альтернативой созданию подкласса UITableView или UITableViewCell (и использованию таймера) было бы просто расширить класс UITableViewCell категорией, например (используя ответ @ oxigen, в данном случае для ячейка вместо таблицы):

@implementation UITableViewCell (DoubleTap)
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    if(((UITouch *)[touches anyObject]).tapCount == 2)
    {
        NSLog(@"DOUBLE TOUCH");
    }
    [super touchesEnded:touches withEvent:event];
}
@end

Таким образом, вам не нужно переименовывать существующие экземпляры UITableViewCell с новым именем класса (будет расширять все экземпляры класса).

Обратите внимание, что теперь super в данном случае (это категория) относится не к UITableView, а к его супер UITView. Но фактический вызов метода для touchesEnded:withEvent: находится в UIResponder (из которых UITView и UITableViewCell являются подклассами), поэтому здесь нет никакой разницы.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...