博客> WKWebView的简单用法
WKWebView的简单用法
1小时前 评论:0 阅读:15 进击的可乐SAMA

准备工作:包含头文件

1.实例化(有两种实例化方法)

//1.简单的初始化
self.webView = [[WKWebView alloc] initWithFrame:];

//2.具有属性的初始化
//创建属性对象
WKWebViewConfiguration * configuration = [[WKWebViewConfiguration alloc] init];
configuration.preferences = [[WKPreferences alloc] init];
//最小的字体号(默认为0)
configuration.preferences.minimumFontSize = n;
//默认为YES
configuration.preferences.javaScriptEnabled = YES;
//是否可以自动通过窗口(即不用用户交互)打开(默认为NO)
configuration.preferences.javaScriptCanOpenWindowsAutomatically = NO;
/*
 注:在dealloc方法中移除
 [self.webView.configuration.userContentController removeAllUserScripts];
 */

self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(n, n, n, n) configuration:configuration];
2.初始化属性

//设置背景色
self.webView.scrollView.backgroundColor = [UIColor whiteColor];

//设置代理
self.webView.navigationDelegate = self;//主要用来追踪加载过程
self.webView.UIDelegate = self;//包含针对于web界面的3种提示框(警告框、确认框、输入框)的弹出事件捕捉

//加载视图
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"xxx"]]];
3.监听加载进度

//添加进度条的属性(estimatedProgress)
[self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
/*
 注:在dealloc中需要移除监听
 [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
 */

//进度条的方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        if (object == self.webView) {
            //处理
        }
     }else{
        //其他.......
    }
}
4.WKNavigationDelegate的方法

//页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    NSLog(@"didStartProvisionalNavigation");
}

//当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    NSLog(@"didCommitNavigation");
}

//页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    NSLog(@"didFinishNavigation");
}

//页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    NSLog(@"didFailProvisionalNavigation");
}

//接收到服务器跳转请求之后调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
    NSLog(@"didReceiveServerRedirectForProvisionalNavigation");
}
收藏
0
sina weixin mail 回到顶部