ios Как сделать, чтобы UITextView обнаруживал одно касание? - PullRequest
10 голосов
/ 25 ноября 2011
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    NSLog(@"touchesBegan");

    //test
    UITouch *touch = [event allTouches] anyObject];
    if ([touch tapCount] == 2) {
        NSLog (@"tapcount 2");
        [self.textview becomeFirstResponder];

    }   

     else if ([touch tapCount] == 1) {
         NSLog (@"tapcount 1");
         [self.textview becomeFirstResponder];
         [self.view performSelector:@selector(select:)];


     }

}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    [super touchesBegan:touches withEvent:event];
    NSLog(@"touchesMoved");
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    NSLog(@"****touchesEnded");
    [self.nextResponder touchesEnded: touches withEvent:event]; 
    NSLog(@"****touchesEnded");
    [super touchesEnded:touches withEvent:event];
    NSLog(@"****touchesEnded");
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event{
    [super touchesCancelled:touches withEvent:event]; 
    NSLog(@"touchesCancelled");
}

МОЙ ВОПРОС:

Я хочу смоделировать два нажатия при однократном нажатии на UITextView, который является просмотром текста в этом коде. Но я не получаю NSLog от одного и двух нажатий, когда я нажимаю один или два раза на просмотр текста, только за его пределами. Что я должен сделать, чтобы это работало?

Ответы [ 3 ]

17 голосов
/ 25 ноября 2011

Вероятно, я бы использовал здесь два распознавателя жестов .

//...some stuff above here probably in you're controllers viewDidLoad

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

UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTapRecognized:)];
doubleTap.numberOfTapsRequired = 2;
[someTextView addGestureRecognizer:doubleTap];
[doubleTap release];

И селекторы будут выглядеть так:

1 голос
/ 18 ноября 2016

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

Этот ответ предназначен для Swift 3.0.В моем решении я реализовал метод делегата textView textViewShouldBeginEditing и возвратил значение false.Это позволяет мне захватывать нажатия на textView без каких-либо дополнительных затрат.

extension ViewController: UITextViewDelegate {
    func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
        // Do something

        return false
    }
}

Просто убедитесь, что textView назначен для использования делегата в вашем классе ViewController.

1 голос
/ 31 июля 2014

У меня была такая же проблема, и другие ответы не работали для меня.Вот что я и сделал.

Я приложил жест, как предложил другой ответ.Затем я убедился, что вызван метод делегата для выбора.Я попытался просто выбрать ячейку, но это не сработало метод делегата.Я считаю, что только пользовательские взаимодействия вызывают метод делегата, поэтому этот код имитирует такое поведение.

https://gist.github.com/brennanMKE/e89bf7a28d96812d6a22

@implementation TappableTextView

- (instancetype)init {
    self = [super init];
    if (self) {
        [self setup];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder {
    self = [super initWithCoder:coder];
    if (self) {
        [self setup];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setup];
    }
    return self;
}

- (void)setup {
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapRecognized:)];
    singleTap.numberOfTapsRequired = 1;
    [self addGestureRecognizer:singleTap];
}

- (void)singleTapRecognized:(id)sender {
    UIView *superview = self.superview;

    UICollectionViewCell *cell = nil;
    NSIndexPath *indexPath = nil;

    while (superview) {
        if ([superview isKindOfClass:[UICollectionViewCell class]]) {
            cell = (UICollectionViewCell *)superview;
        }

        if ([superview isKindOfClass:[UICollectionView class]] && cell) {
            UICollectionView *collectionView = (UICollectionView *)superview;
            indexPath = [collectionView indexPathForCell:cell];
            NSAssert(collectionView.delegate, @"Delegate must be defined");
            NSAssert([collectionView.delegate respondsToSelector:@selector(collectionView:didSelectItemAtIndexPath:)], @"Selection must be supported");
            if (indexPath && [collectionView.delegate respondsToSelector:@selector(collectionView:didSelectItemAtIndexPath:)]) {
                [collectionView.delegate collectionView:collectionView didSelectItemAtIndexPath:indexPath];
            }

            return;
        }

        superview = superview.superview;
    }
}

@end
...