7

Total Objective-C / Cocoa Touch noob here, beware.

I'm trying to intercept when a user long presses on a UITextView (a magnifying glass then appears with the caret positioner) and then releases the touch, i.e. when normally the "Select" and "Select All" Options appear, after the magnifying glass. I want to replace this with my own custom action that is then performed.

Is this possible?

Epaga
  • 38,231
  • 58
  • 157
  • 245

3 Answers3

15

You can try something like this:

Disable the built-in long press recognizer

for (UIGestureRecognizer *recognizer in textView.gestureRecognizers) {
  if ([recognizer isKindOfClass:[UILongPressGestureRecognizer class]]){
    recognizer.enabled = NO;
  }
}

Then add your own

UILongPressGestureRecognizer *myLongPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:<your target> action:@selector(<your custom handler>)]; 
[textView addGestureRecognizer:myLongPressRecognizer];
[myLongPressRecognizer release];
Altealice
  • 3,572
  • 3
  • 21
  • 41
  • This looks good...but is there any way for me to keep the magnifying glass? What I'm mainly interested in is the release of the long press AFTER the magnifying glass- – Epaga Oct 09 '10 at 07:59
  • Hmm, haven't tried that before. You can try overriding the method that handles the magnifying glass to add your handling when it ends, but it's probably a private method, so that may not work out well with Apple's review team. The other way is to re-implement the magnifying glass yourself. – Altealice Oct 12 '10 at 16:58
  • 2
    I like the thinking here, but sadly this approach does not work. Might be a private buried subview inside UITextView that gets the recognizer? – BadPirate May 20 '11 at 19:15
  • I guess you can try to search for that subview then. You can loop through them by using '[textView subviews]'. I can't give any guarantees though. – Altealice May 20 '11 at 20:01
2

Swift version of @Altealice's code to disable the built-in long press recognizer:

if let actualRecognizers = self.sourcesTextView.gestureRecognizers {
    for recognizer in actualRecognizers {
        if recognizer.isKindOfClass(UILongPressGestureRecognizer) {
            recognizer.enabled = false
        }
    }
}

This solution works but beware that it's gonna disable the textView interactions, so the links won't be highlighted when pressed and the text won't be selectable.

Luca De Angelis
  • 227
  • 4
  • 12
0

if you remove the [LongPressgesture setMinimumPressDuration:2.0]; it will work .. since the tab gesture will be called to start edit the textField ... or just implement this gesture delegate function

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}
Azhar
  • 20,500
  • 38
  • 146
  • 211