cra*_*ash 15 iphone uitextview iphone-sdk-3.0 ios
我正在开发和iPhone 3.0应用程序.我正在尝试将UITextView中的Web链接打开到UIWebView而不是Safari.但仍然没有运气.
这UITextView是不可编辑的,它可以完美地检测Web链接并在Safari中打开它们.
怎么避免呢?如何获取该网址,以便我可以使用我自己的UIWebView?
小智 20
这是一个古老的问题,但任何人都在寻找更新的方式.
在viewController的.m文件中将您的viewController分配为一个委托UITextView,只需添加:
-(BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange{
//Do something with the URL
NSLog(@"%@", URL);
return NO;
}
Run Code Online (Sandbox Code Playgroud)
最简单的方法是像这样覆盖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
Run Code Online (Sandbox Code Playgroud)
这将影响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
Run Code Online (Sandbox Code Playgroud)
以下代码显示如何在Safari应用中打开UITextViewWeb链接SFSafariViewController而不是打开它们:
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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7544 次 |
| 最近记录: |