iOS-UIWebView的一些用法(js調oc方法)

來源:互聯網
上載者:User

標籤:



  • 源: http://www.jianshu.com/p/c38a8a8edcf0

  • UIWebView載入遠程url
    NSURL *url = [NSURL URLWithString:@"[http://www.baidu.com]"];NSURLRequest *request = [NSURLRequest requestWithURL:url];[self.webView loadRequest:request];
  • UIWebView載入本地html

    方法1
      //載入本地html    NSString *basePath = [[NSBundle mainBundle] bundlePath];    NSString *htmlPath = [basePath stringByAppendingPathComponent:@"test.html"];    NSURL *url = [NSURL fileURLWithPath:htmlPath];    NSURLRequest *request = [NSURLRequest requestWithURL:url];    [self.webView loadRequest:request];    
    方法2
      NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"html"];    NSURL *url = [NSURL URLWithString:path];    self.webView.scalesPageToFit = YES;    NSString *htmlString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];    [self.webView loadHTMLString:htmlString baseURL:url];    
  • JS調用OC方法

    網上有開源架構,可以實現native 和 js直接互相調用 WebViewJavascriptBridge,如果只是需要簡單的調用的話,完全可以利用UIWebView的代理方法代替- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType,代碼如下:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{NSString *url = [[request URL] absoluteString];//    NSURL *url = [request URL];NSLog(@"%@",url);//代碼中根據返回的URL或者scheme來判斷處理不同邏輯if ([url isEqualToString:@"demo://"]){DetailViewController *detail = [[DetailViewController alloc] init];[self.navigationController pushViewController:detail animated:YES];}return YES;}
html代碼如下:
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>測試網頁</title><script type="text/javascript">function demo(){<!--    alert(1212);-->window.location.href="demo://";}</script><style type="text/css">/*div{border-radius: 30px;background-color: yellow;position: relative;}*/button{font-size: 40px;background-color: red;padding-top: 10px;margin: 30px;position: relative;left: 29%;}</style></head><body><div></br></br></br></br></br></br></br><button onclick = "demo()" >按鈕事件</button></div></body></html>

iOS-UIWebView的一些用法(js調oc方法)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.