美文网首页iOS
WKWebView添加进度条 - iOS

WKWebView添加进度条 - iOS

作者: HAKA | 来源:发表于2017-03-23 15:43 被阅读45次
    #import "ViewController.h"
    #include <WebKit/WebKit.h>
    @interface ViewController ()
    @property(nonatomic,strong)WKWebView *testWebView;
    @property(nonatomic,strong)UIProgressView *progressView;
    @end
    // 屏幕高度
    #define SCREEN_HEIGHT         [[UIScreen mainScreen] bounds].size.height
    // 屏幕宽度
    #define SCREEN_WIDTH          [[UIScreen mainScreen] bounds].size.width
    
    @implementation ViewController
    
    - (void)viewDidLoad {
    [super viewDidLoad];
    // 初始化 wkwebView
    _testWebView = [[WKWebView alloc]init];
    _testWebView.frame = CGRectMake(0, 20, SCREEN_WIDTH, SCREEN_HEIGHT);
    [self.view addSubview:_testWebView];
    
    // 设置进度条
    _progressView = [[UIProgressView alloc]init];
    _progressView.frame = CGRectMake(0, 20, SCREEN_WIDTH, 5);
    _progressView.backgroundColor = [UIColor greenColor];
    [self.view addSubview:_progressView];
    // 添加监测
    [_testWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew| NSKeyValueObservingOptionOld context:nil];
    [_testWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com"]]];
    
    
    // Do any additional setup after loading the view, typically from a nib.
    }
    // 实现监测
    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    NSLog(@" %s,change = %@",__FUNCTION__,change);
    if ([keyPath isEqual: @"estimatedProgress"] && object == _testWebView) {
        [self.progressView setAlpha:1.0f];
        [self.progressView setProgress:_testWebView.estimatedProgress animated:YES];
        if(_testWebView.estimatedProgress >= 1.0f)
        {
            [UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
                [self.progressView setAlpha:0.0f];
            } completion:^(BOOL finished) {
                [self.progressView setProgress:0.0f animated:NO];
            }];
        }
    }
    else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
    }
    
    
    
    
    - (void)dealloc {
    [_testWebView removeObserver:self forKeyPath:@"estimatedProgress"];
    // if you have set either WKWebView delegate also set these to nil here
    [_testWebView setNavigationDelegate:nil];
    [_testWebView setUIDelegate:nil];
    }
    

    相关文章

      网友评论

        本文标题:WKWebView添加进度条 - iOS

        本文链接:https://www.haomeiwen.com/subject/avzznttx.html