- 源: 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>
@import url(http://i.cnblogs.com/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);
时间: 2024-10-10 23:45:48