当我单击 UIWebview(它就像广告显示)时,我试图在 safari 中打开一个链接。 以下代码正在使用,但发生的情况是当我单击 webview 它在 UIWebview 中打开某些链接(不是全部)时。
- (BOOL)webView:(UIWebView *)webView1 shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
if (webView1==webview) {
if (UIWebViewNavigationTypeLinkClicked == navigationType) {
[[UIApplication sharedApplication] openURL:[request URL]];
return NO;
}
return YES;
}
}
这里发生的情况是,如果该 UIWebView 中有任何文本链接,那么它会正确打开,但是如果 UIWebview 带有图像,那么它会在同一个 UIWebview 而不是新浏览器中打开。
我当前的代码
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.example.com/files/ad.htm"]]];
[_webView setBackgroundColor:[UIColor clearColor]];
[_webView setOpaque:NO];
_webView.scrollView.bounces = NO;
}
-(BOOL) webView:(UIWebView *)inWeb shouldStartLoadWithRequest:(NSURLRequest *)inRequest navigationType:(UIWebViewNavigationType)inType {
if ( inType == UIWebViewNavigationTypeLinkClicked ) {
[[UIApplication sharedApplication] openURL:[inRequest URL]];
return NO;
}
return YES;
}
最佳答案
似乎这些图像已使用 anchor 标记链接...
试试这个...
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
static NSString *reguler_exp = @"^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9-]*[a-zA-Z0-9])[.])+([A-Za-z]|[A-Za-z][A-Za-z0-9-]*[A-Za-z0-9])$";
//Regular expression to detect those certain tags..You can play with this regular expression based on your requirement..
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", reguler_exp];
//predicate the matched tags.
if ([resultPredicate evaluateWithObject:request.URL.host]) {
[[UIApplication sharedApplication] openURL:request.URL];
return NO;
} else {
return YES;
}
}
编辑:不允许第一次调用此委托(delegate)方法。添加一些不会在第一次加载 webview 时调用它的逻辑。
(SOP的新要求,见下方评论)
如何检测uiwebview上的触摸,
1) 将点击手势添加到您的 webview。(在此之前,在您的 viewcontroller.h 中添加 UIGestureRecognizerDelegate)
例子:
UITapGestureRecognizer* singleTap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleSingleTap:)];
singleTap.numberOfTouchesRequired=1;
singleTap.delegate=self;
[webview addGestureRecognizer:singleTap];
2)然后添加这个委托(delegate)方法,
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
//return YES,if you want to control the action natively;
//return NO,in case your javascript does the rest.
}
注意:如果您想检查触摸是原生的还是 html(javascript),请查看不错的小教程 here ,关于处理 javascript 事件等......希望这对你有帮助..
关于html - 单击 UIWebView 时如何在 Safari 中打开链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18374734/