我正在开发 iPhone 3.0 应用程序。我正在尝试将 UITextView 中的 Web 链接打开到 UIWebView 而不是 Safari 中。但仍然没有运气。
UITextView
不可编辑,它可以完美地检测 Web 链接并在 Safari 中打开它们。
如何避免这种情况?如何获取该网址以便我可以自己使用UIWebView
?
我正在开发 iPhone 3.0 应用程序。我正在尝试将 UITextView 中的 Web 链接打开到 UIWebView 而不是 Safari 中。但仍然没有运气。
UITextView
不可编辑,它可以完美地检测 Web 链接并在 Safari 中打开它们。
如何避免这种情况?如何获取该网址以便我可以自己使用UIWebView
?
这是一个老问题,但如果有人正在寻找更新的方法来做到这一点。
在 viewController 的 .m 文件中分配包含 UITextView 作为委托的 viewController,然后添加:
-(BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange{
//Do something with the URL
NSLog(@"%@", URL);
return NO;
}
最简单的方法是像这样覆盖webView:decidePolicyForNavigationAction:request:frame:decisionListener:
方法UITextView
:
@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
您的应用程序中的所有 s。如果您只在单个视图上需要它,请创建一个子类并覆盖其上的方法。
注意:这在技术上是一个私有 API,可以随时删除。无法通过公共 API 执行此操作。
编辑:从 iOS 7.0 开始,引入了一种新方法UITextViewDelegate
来支持这一点。有关详细信息,请参阅 nihad 的答案。
使用 Swift 3,UITextViewDelegate
提供了一种textView(_:shouldInteractWith:in:interaction:)
方法。textView(_:shouldInteractWith:in:interaction:)
有以下声明:
询问委托指定的文本视图是否应允许在给定文本范围内与给定 URL 进行指定类型的用户交互。
optional func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool
以下代码显示了如何UITextView
在 a 中打开 Web 链接,SFSafariViewController
而不是在 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
}
}