How to intercept click on link in UITextView?

2019-01-02 17:54发布

问题:

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.

回答1:

Update: From ios10,

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

From ios7 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 ios6 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.



回答2:

In iOS 7 or Later

You can use the following UITextView delegate Method:

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

The text view calls this method if the user taps or long-presses the URL link. Implementation of this method is optional. By default, the text view opens the application responsible for handling the URL type and passes it the URL. You can use this method to trigger an alternative action, such as displaying the web content at the URL in a web view within the current application.

Important:

Links in text views are interactive only if the text view is selectable but noneditable. That is, if the value of the UITextView the selectable property is YES and the isEditable property is NO.



回答3:

For Swift 3

textView.delegate = self

extension MyTextView: UITextViewDelegate 

    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {

        GCITracking.sharedInstance.track(externalLink: URL)
        return true
    }
}

or if target is >= IOS 10

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool


回答4:

Swift version:

Your standard UITextView setup should look something like this, don't forget the delegate and dataDetectorTypes.

var textView = UITextView(x: 10, y: 10, width: CardWidth - 20, height: placeholderHeight) //This is my custom initializer
textView.text = "dsfadsaf www.google.com"
textView.selectable = true
textView.dataDetectorTypes = UIDataDetectorTypes.Link
textView.delegate = self
addSubview(textView)

After your class ends add this piece:

class myVC: UIViewController {
    //viewdidload and other stuff here
}

extension MainCard: UITextViewDelegate {
    func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool {
        //Do your stuff over here
        var webViewController = SVModalWebViewController(URL: URL)
        view.presentViewController(webViewController, animated: true, completion: nil)
        return false
    }
}


回答5:

With Swift 3 and i0S 10, the simplest way to interact with phone numbers, urls or addresses in UITextView is to use UIDataDetectorTypes. The code below shows how to display a phone number in a UITextView so that the user can interact with it.

import UIKit

class ViewController: UIViewController {

    // Link this outlet to a UITextView in your Storyboard
    @IBOutlet weak var textView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()

        textView.text = "+33687654321"
        textView.isUserInteractionEnabled = true // default: true
        textView.isEditable = false // default: true
        textView.isSelectable = true // default: true
        textView.dataDetectorTypes = [.phoneNumber]
    }

}

With this code, when clicking on the phone number, a UIAlertController will pop up.


As an alternative, you can use NSAttributedString:

import UIKit

class ViewController: UIViewController {

    // Link this outlet to a UITextView in your Storyboard
    @IBOutlet weak var textView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let phoneUrl = NSURL(string: "tel:+33687654321")! // "telprompt://+33687654321" also works
        let attributes = [NSLinkAttributeName: phoneUrl]
        let attributedString = NSAttributedString(string: "phone number", attributes: attributes)

        textView.attributedText = attributedString
        textView.isUserInteractionEnabled = true // default: true
        textView.isEditable = false // default: true
        textView.isSelectable = true // default: true
    }

}

With this code, when clicking on the attributed string, a UIAlertController will pop up.


However, you may want to perform some custom action instead of making a UIAlertController pop up when you click on a phone number. Or you may want to keep a UIAlertController to pop up and perform your own custom action in the same time.

In both cases, you will have to make your UIViewController conform to UITextViewDelegate protocol and implement textView(_:shouldInteractWith:in:interaction:). The code below shows how to do it.

import UIKit

class ViewController: UIViewController, UITextViewDelegate {

    // Link this outlet to a UITextView in your Storyboard
    @IBOutlet weak var textView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()

        textView.delegate = self

        textView.text = "+33687654321"
        textView.isUserInteractionEnabled = true
        textView.isEditable = false
        textView.isSelectable = true
        textView.dataDetectorTypes = [.phoneNumber]
    }

    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        /* perform your own custom actions here */
        print(URL)

        return false // return true if you still want UIAlertController to pop up
    }

}

With this code, when clicking on the phone number, no UIAlertController will pop up and you will instead get the following print in your console:

tel:+33687654321



回答6:

I have dynamic content in text view , which may contain link. The shouldInteractWithURL is getting called only when user is long press on link but not calling on tap of link. Please redirect if any buddy has reference to it.

Following is some of the code sniped.

UITextView *ltextView = [[UITextView alloc] init];
[ltextView setScrollEnabled:YES];
[ltextView setDataDetectorTypes:UIDataDetectorTypeLink];
ltextView.selectable = YES;
[ltextView setEditable:NO];
ltextView.userInteractionEnabled = YES;
ltextView.delegate = (id)self;
ltextView.delaysContentTouches = NO;
[self.view addsubview:ltextview];

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange{

    [self.mActionDelegate userClickedOnImageLinkFromWebview:URL];

    NSLog(@"urls is :- %@",URL);
    return FALSE;
}

The above delegate method is not getting called on tap.

Regards, Rohit Jankar



回答7:

Swift 4:

1) Create the following class (subclassed UITextView):

import Foundation

protocol QuickDetectLinkTextViewDelegate: class {
    func tappedLink()
}

class QuickDetectLinkTextView: UITextView {

    var linkDetectDelegate: QuickDetectLinkTextViewDelegate?

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)

    }

    required init?(coder aDecoder: NSCoder) {
         super.init(coder: aDecoder)
    }

    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        let glyphIndex: Int? = layoutManager.glyphIndex(for: point, in: textContainer, fractionOfDistanceThroughGlyph: nil)
        let index: Int? = layoutManager.characterIndexForGlyph(at: glyphIndex ?? 0)
        if let characterIndex = index {
            if characterIndex < textStorage.length {
                if textStorage.attribute(NSLinkAttributeName, at: characterIndex, effectiveRange: nil) != nil {
                    linkDetectDelegate?.tappedLink()
                    return self
                }
            }
        }

        return nil
    }
}


2) Wherever you set up your textview, do this:

//init, viewDidLoad, etc
textView.linkDetectDelegate = self

//outlet
@IBOutlet weak var textView: QuickDetectLinkTextView!

//change ClassName to your class
extension ClassName: QuickDetectLinkTextViewDelegate {
    func tappedLink() {
        print("Tapped link, do something")
    }
}


If you're using storyboard, make sure your textview looks like this in the right pane identity inspector:



Voila! Now you get the link tap immediately instead of when the URL shouldInteractWith URL method



回答8:

I haven't tried that myself but you can try to implement application:handleOpenURL: method in your application delegate - it looks like all openURL request pass through this callback.



回答9:

Not sure how you would intercept the detected data link, or what type of function you need to run. But you may be able to utilize the didBeginEditing TextField method to run a test/scan through the textfield if you know what your looking for..such as comparing text strings that meet ###-###-#### format, or begin with "www." to grab those fields, but you would need to write a little code to sniff through the textfields string, reconize what you need, and then extract it for your function's use. I don't think this would be that difficult, once you narrowed down exactly what it is that you wanted and then focussed your if() statement filters down to very specific matching pattern of what you needed.

Of couse this implies that the user is going to touch the textbox in order to activate the didBeginEditing(). If that is not the type of user interaction you were looking for you could just use a trigger Timer, that starts on ViewDidAppear() or other based on need and runs through the textfields string, then at the end of you run through the textfield string methods that you built, you just turn the Timer back off.



回答10:

application:handleOpenURL: is called when another app opens your app by opening a URL with a scheme your app supports. It's not called when your app begins opening a URL.

I think the only way to do what Vladimir wants is to use a UIWebView instead of a UITextView. Make your view controller implement UIWebViewDelegate, set the UIWebView's delegate to the view controller, and in the view controller implement webView:shouldStartLoadWithRequest:navigationType: to open [request URL] in a view instead of quitting your app and opening it in Mobile Safari.



标签: