[英]Detect tapped image inside UIWebView
我有一個網絡視圖,顯示由他人完成的html + js簡介。 當用戶點擊特定的圖像時,我需要執行搜索。 我不懂JavaScript。 如果我嘗試使用.src返回空值,如果嘗試.innerHTML則總是返回很多代碼。 如何檢測這種特定的觸摸? 謝謝。
- (void)viewDidLoad
{
[super viewDidLoad];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
[tap setDelegate:self];
[self.webView.scrollView addGestureRecognizer:tap];
NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"myFile" ofType:@"html" inDirectory:@"myDir"];
NSURL* url = [[NSURL alloc]initFileURLWithPath:htmlFile];
NSURLRequest* request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
return YES;
}
-(void)viewTapped:(UITapGestureRecognizer*)tap {
CGPoint touchPoint = [tap locationInView:self.webView];
NSString *js = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", touchPoint.x, touchPoint.y];
NSString *urlToSave = [self.webView stringByEvaluatingJavaScriptFromString:js];
//Returning an empty string
if (urlToSave.length > 0) {
[self performSegueWithIdentifier:@"introToMain" sender:self];
}
}
我認為您應該使html中的圖片可點擊。 如果是這樣,請忽略此。 然后,您應該使用UIWebView的shouldStartLoadWithRequest委托方法,如下所示:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
if (navigationType == UIWebViewNavigationTypeLinkClicked){
NSURL *url = request.URL;
//Maybe you can detect the image here looking to the url.
}
return YES;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.