WKWebView的使用,利用KVO

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

#import <UIKit/UIKit.h>

@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 <WebKit/WebKit.h>

@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<NSString *,id> *)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];



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值