Monday, April 11, 2016

Making hyperlinks in UITextView to respond instantly

Ever wondered why hyperlinks in UITextView responds only when you touch and hold for a few seconds,whereas hyperlink in web view works much faster.

I assume its designed in that way.Am sure you have checked those initial set ups like   textview.selectable=yes.

I solved it through help from stack overflow post http://stackoverflow.com/questions/22379595/uitextview-link-tap-recognition-is-delayed 

Solution:

1.Add a Tap gesture to UITextview.

UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tappedTextView:)];
[myTextView addGestureRecognizer:tapRecognizer];

2.In the handle method get the touch position


    CGPoint tapLocation = [tapGesture locationInView:textView];

 and get the Attributes of the text whose points closest to the touch
    UITextPosition *textPosition = [textView closestPositionToPoint:tapLocation];
    NSDictionary *attributes = [textView textStylingAtPosition:textPosition inDirection:UITextStorageDirectionForward];

3.Get URL from the attributes and open the url if its not null

    NSURL *url = attributes[NSLinkAttributeName];

    if (url) {
        [[UIApplication sharedApplication] openURL:url];
    }

No comments:

Post a Comment