热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

WKWebView的使用,利用KVO

TGWebVC.hCreatedbytargetcloudon201737.Copyright©2017年targetcloud.
//
//  TGWebVC.h
//
//  Created by targetcloud on 2017/3/7.
//  Copyright © 2017年 targetcloud. All rights reserved.
//

#import 

@interface TGWebVC : UIViewController
@property (nonatomic, strong) NSURL *url;
@end


//
//  TGWebVC.m
//
//  Created by targetcloud on 2017/3/7.
//  Copyright © 2017年 targetcloud. All rights reserved.
//

#import "TGWebVC.h"
#import 

@interface TGWebVC ()
@property (weak, nonatomic) IBOutlet UIView *contentV;
@property (weak, nonatomic) IBOutlet WKWebView *webV;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *backItem;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *forwardItem;
@property (weak, nonatomic) IBOutlet UIProgressView *progressV;
@end

@implementation TGWebVC

- (IBAction)goBack:(id)sender {
    [self.webV goBack];
}

- (IBAction)goForward:(id)sender {
    [self.webV goForward];
}

- (IBAction)reload:(id)sender {
    [self.webV reload];
}

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    _webV.frame = self.contentV.bounds;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    WKWebView *webView = [[WKWebView alloc] init];
    _webV = webView;
    [self.contentV addSubview:webView];
    NSURLRequest *request = [NSURLRequest requestWithURL:_url];
    [webView loadRequest:request];
    [webView addObserver:self forKeyPath:@"canGoBack" options:NSKeyValueObservingOptionNew context:nil];
    [webView addObserver:self forKeyPath:@"canGoForward" options:NSKeyValueObservingOptionNew context:nil];
    [webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    [webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    self.backItem.enabled = self.webV.canGoBack;
    self.forwardItem.enabled = self.webV.canGoForward;
    self.title = self.webV.title;
    self.progressV.progress = self.webV.estimatedProgress;
    self.progressV.hidden = self.webV.estimatedProgress >= 1;
}

- (void)dealloc{
    [self.webV removeObserver:self forKeyPath:@"canGoBack"];
    [self.webV removeObserver:self forKeyPath:@"title"];
    [self.webV removeObserver:self forKeyPath:@"canGoForward"];
    [self.webV removeObserver:self forKeyPath:@"estimatedProgress"];
}

@end

调用示例:

    TGWebVC *webVc = [[TGWebVC alloc] init];
    webVc.url = [NSURL URLWithString:item.url];
    [self.navigationController pushViewController:webVc animated:YES];




推荐阅读
author-avatar
手机用户2602903715
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有