我已经在UITextView上指定了dataDetectorTypes,以便当用户点击URL时在Safari中打开。
是否有可能拦截此行为,以便我可以在UIWebView中加载URL?还是我需要编写自己的URL检测器代码来重新路由?
我已经在UITextView上指定了dataDetectorTypes,以便当用户点击URL时在Safari中打开。
是否有可能拦截此行为,以便我可以在UIWebView中加载URL?还是我需要编写自己的URL检测器代码来重新路由?
在用户点击URL时,您需要进行URL检测并手动加载UIWebView。
由于苹果会将所有的http://
和https://
URL打开Safari,所以一切都需要定制化处理。
int retVal = UIApplicationMain(argc, argv, @"MyApplicationSubclass", nil);
我为大家做了一件好事,用博客文章和演示应用程序回答了你的问题。
http://52apps.net/post/879106231/method-swizzling-uitextview-and-safari
http://github.com/marksands/UITextViewLinkOptions
为了进一步解释tt.Kilew的帖子,您可以创建类别,但将方法命名为其他名称,例如customOpenURL
。当您想返回Safari时,您需要进行一种称为方法交换的操作。代码如下:
#import <objc/runtime.h>
..
Method customOpenUrl = class_getInstanceMethod([UIApplication class], @selector(customOpenURL:));
Method openUrl = class_getInstanceMethod([UIApplication class], @selector(openURL:));
method_exchangeImplementations(customOpenUrl, openUrl);
当你想要或不想使用Safari时,只需调用此方法以交换openURL
实现和customOpenURL
实现。
查看演示应用程序以获取更多详细信息。希望这可以帮助你! :)
如果您不想冒险被拒绝,您可能需要查看我开发的自定义UITextView以更好地适应情况:https://github.com/marksands/MSTextView
Swift版本:
您的标准UITextView设置应该类似于这样,不要忘记委托和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)
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
}
}
另一个答案 :) 对我来说有效的方法是重新实现UIApplication openURL:(NSURL *) url
@interface UIApplication (Private)
- (BOOL)openURL:(NSURL*)url;
@end
@implementation UIApplication (Private)
- (BOOL)openURL:(NSURL*)url {
// all viewcontrollers should change currentViewController to self
if ([MyWatcher currentViewController]) {
// Do anything you want
[[MyWatcher handleURL:url withController:[MyWatcher currentViewController]];
return YES;
}
return NO;
}
@end
... Some view controller
- (void)viewDidLoad {
[super viewDidLoad];
[MyWatcher setCurrentController:self];
}
application:handleOpenURL:
方法。每当一个URL被打开时,这个方法都会被调用。在这里,你应该能够让URL在你的Web视图中打开。