Preventing Text Selection in UITextView with Auto Detection On

Here something a little obscure. When your using a UITextView and you want it to detect things like link, phone numbers, addresses and events you must have “Selectable” set to YES. Which is great except, Selectable also means it selects text when all you really want your user to do is tap a link. How do you prevent Text Selection without turning off Selectable?

Here is my take. I created a Category for UITextView but obviously this isn’t totally necessary and I also assumed that you only want this to happen when you also have “Editing” turned off. Which by the way is required for auto detection.

UITextView+Selectable.h

#import <UIKit/UIKit.h>
@interface UITextView (Selectable) @end
UITextView+Selectable.m

#import "TextView+Selectable.h"
@implementation UITextView (Selectable)
//If Editable = NO
//Prevent text selection through double tapping

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {

    if(self.editable == NO){
        if ([gestureRecognizer isKindOfClass: [UITapGestureRecognizer class] ] && [(UITapGestureRecognizer*) gestureRecognizer numberOfTapsRequired] == 2) {
            if([gestureRecognizer isMemberOfClass:[UITapGestureRecognizer class]]){
                return YES;
            }
            else{
                return NO;
            }
        }
    }
    return [super gestureRecognizerShouldBegin:gestureRecognizer];}
@end

So, all we are doing is checking if a gesture is a double tap and saying NO if it is. As an added bonus we are permitting any double taps we created by testing for the UITapGestureRecognizer class, Apple uses private classes that are kinds of UITapGestureRecognizer. I use the double tap to disable auto detection and turn editing back on.

Hope this is helpful! And as alway, “Your mileage may vary!”

Ken

 

 

 

This entry was posted in General. Bookmark the permalink.

Leave a Reply