一、UIWebView的基本使用
UIWebView 的四个代理方法:
#pragma mark UIWebViewDelegate
//即将请求网页
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
NSLog(@"Request URL %@",request.URL);
return YES;
}
//开始加载网面
-(void)webViewDidStartLoad:(UIWebView *)webView{
NSLog(@"webViewDidStartLoad");
}
//网页加载完成
-(void)webViewDidFinishLoad:(UIWebView *)webView{
NSLog(@"webViewDidFinishLoad");
}
//网页加载出错
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
NSLog(@"didFailLoadWithError");
}
UIWebView常用方法
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//加载URL
NSURL *url = [[NSURL alloc] initWithString:@"http://www.baidu.com"];
NSURLRequest *req = [[NSURLRequest alloc] initWithURL:url];
//加载本地HTML
NSString *localHTMLPageFilePath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
NSURL *localHTMLPageFileURL = [NSURL fileURLWithPath:localHTMLPageFilePath];
req = [NSURLRequest requestWithURL:localHTMLPageFileURL];
//禁止webveiw滚动
//self.webView.scrollView.bounces = NO;
//设置webview的背景颜色
//[self.webView setBackgroundColor:[UIColor blueColor]];
//移除滚动后的外边阴影
UIScrollView *scrollView = self.webView.scrollView;
for (int i = 0; i < scrollView.subviews.count ; i++) {
UIView *view = [scrollView.subviews objectAtIndex:i];
if ([view isKindOfClass:[UIImageView class]]) {
view.hidden = YES ;
}
}
[self.webView loadRequest:req];
}
点击html中的按钮弹出原生的提示框,实现的代码如下,html页面
<!DOCTYPE html>
<html>
<head>
<title>html</title>
<meta charset="utf-8">
<script type="text/javascript">
function sendMsg(cmd,param){
var url = "JS2OC://"+cmd+":"+param;
document.location = url;
}
</script>
</head>
<body>
UserName <input type="text" id="input"><br/>
<input type="button" value="SendMsg" οnclick="sendMsg('alert','hello')">
</body>
</html>
在ViewController.m文件中编写
#pragma mark UIWebViewDelegate
//即将请求网页
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
NSLog(@"Request URL %@",request.URL);
NSString *url =[[request URL] absoluteString];
if([url hasPrefix:@"JS2OC://"])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"JS调用OC" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[alert show];
}
return YES;
}
实现的效果如下图