How to intercept click on link in UITextView?

Vladimir picture Vladimir · Mar 30, 2010 · Viewed 64.9k times · Source

Is it possible to perform custom action when user touch autodetected phone link in UITextView. Please do not advice to use UIWebView instead.

And please don't just repeat text from apple classes reference - certainly I've already read it.

Thanks.

Answer

fsaint picture fsaint · Dec 2, 2010

Update: From ,

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction;

From and Later UITextView has the delegate method:

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange *NS_DEPRECATED_IOS(7_0, 10_0, "Use textView:shouldInteractWithURL:inRange:forInteractionType: instead");*

to intercept the clicks to links. And this is the best way to do it.

For and earlier a nice way to do this is to by subclassing UIApplication and overwriting the -(BOOL)openURL:(NSURL *)url

@interface MyApplication : UIApplication {

}

@end

@implementation MyApplication


-(BOOL)openURL:(NSURL *)url{
    if  ([self.delegate openURL:url])
         return YES;
    else
         return [super openURL:url];
}
@end

You will need to implement openURL: in your delegate.

Now, to have the application start with your new subclass of UIApplication, locate the file main.m in your project. In this small file that bootstraps your app, there is usually this line:

int retVal = UIApplicationMain(argc, argv, nil, nil);

The third parameter is the class name for your application. So, replacing this line for:

int retVal = UIApplicationMain(argc, argv, @"MyApplication", nil);

This did the trick for me.