IOS开发 UIWebView使用详解(2)

一、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];
}


js与oc交互
点击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;
}

实现的效果如下图





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值