以下是iOS的WKWebView进度条监听代码:

  1. 首先,要在ViewController的类定义中添加WKNavigationDelegate协议。例如:

@interface ViewController : UIViewController

  1. 在ViewController.m文件中,添加以下代码:
  • (void)viewDidLoad { [super viewDidLoad];

    // 初始化WKWebView WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds]; webView.navigationDelegate = self; [self.view addSubview:webView];

    // 添加进度条 UIProgressView *progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 64, self.view.bounds.size.width, 2)]; progressView.tintColor = [UIColor blueColor]; progressView.trackTintColor = [UIColor clearColor]; [self.view addSubview:progressView];

    // 监听进度 [webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];

    // 加载网页 NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.google.com"]]; [webView loadRequest:request]; }

  • (void)dealloc { // 移除监听 [self.webView removeObserver:self forKeyPath:@"estimatedProgress"]; }

#pragma mark - WKNavigationDelegate

  • (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation { // 开始加载网页时,显示进度条 self.progressView.hidden = NO; }

  • (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation { // 网页加载完成后,隐藏进度条 self.progressView.hidden = YES; }

#pragma mark - KVO监听进度

  • (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context { if ([keyPath isEqualToString:@"estimatedProgress"]) { // 更新进度条 float progress = [[change objectForKey:NSKeyValueChangeNewKey] floatValue]; self.progressView.progress = progress; } }

注意:在dealloc方法中要移除监听,否则会出现问题

iOS的wkwebview进度条监听代码

原文地址: https://www.cveoy.top/t/topic/hgyo 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录