如何在UIWebView而不是Safari中打开UITextView网页链接?

我正在开发和iPhone 3.0应用程序。 我试图打开UITextView的网页链接到UIWebView而不是Safari。 但是还是没有运气。

UITextView是不可编辑的,它完美地检测网页链接并在Safari中打开它们。

如何避免? 如何抓住这个url,所以我可以使用我自己的UIWebView

最简单的方法是覆盖UITextView上的webView:decidePolicyForNavigationAction:request:frame:decisionListener:方法,如下所示:

 @interface UITextView (Override) @end @class WebView, WebFrame; @protocol WebPolicyDecisionListener; @implementation UITextView (Override) - (void)webView:(WebView *)webView decidePolicyForNavigationAction:(NSDictionary *)actionInformation request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id < WebPolicyDecisionListener >)listener { NSLog(@"request: %@", request); } @end 

这将影响您的应用程序中的所有UITextView 。 如果你只在一个视图上需要这个,创build一个子类并重写这个方法。

注意:这在技术上是一个私人的API,可以在任何时候被删除。 没有办法通过公共API来做到这一点。

编辑:从iOS 7.0开始, UITextViewDelegate引入了一个新的方法来支持这个方法。 详情请看nihad的回答。

这是一个古老的问题,但任何人都在寻找一个更新的方式来做到这一点。

将你的viewController分配给你的viewController的.m文件,并保存UITextView作为一个委托,然后添加:

 -(BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange{ //Do something with the URL NSLog(@"%@", URL); return NO; } 

用Swift 3, UITextViewDelegate提供了一个textView(_:shouldInteractWith:in:interaction:)方法。 textView(_:shouldInteractWith:in:interaction:)具有以下声明:

询问委托人是否指定的文本视图应允许指定types的用户与指定范围的文本中的给定URL进行交互。

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

以下代码显示了如何在SFSafariViewController打开UITextView Web链接,而不是在Safari应用程序中打开它们:

 import UIKit import SafariServices class ViewController: UIViewController, UITextViewDelegate { override func viewDidLoad() { super.viewDidLoad() // Set textView let textView = UITextView() textView.text = "http://www.yahoo.fr http://www.google.fr" textView.isUserInteractionEnabled = true textView.isEditable = false textView.isSelectable = true textView.dataDetectorTypes = UIDataDetectorTypes.link // Add view controller as the textView's delegate textView.delegate = self // auto layout view.addSubview(textView) textView.translatesAutoresizingMaskIntoConstraints = false textView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true textView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true textView.heightAnchor.constraint(equalToConstant: 300).isActive = true textView.widthAnchor.constraint(equalToConstant: 300).isActive = true } func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool { // Open links with a SFSafariViewController instance and return false to prevent the system to open Safari app let safariViewController = SFSafariViewController(url: URL) present(safariViewController, animated: true, completion: nil) return false } }