All along, there is a technical blog to record the summary of their work encountered in the idea of the problem, the idea dragged on for a long time today only began to write their first technical blog, because just started to write, inevitably will appear wrong place, I hope you see Daniel many advice. OK, don't say more, go straight to the point ~
Wkwebview has an attribute estimatedprogress, which is the progress of the current page load and can be monitored by KVO.
Wkwebview * WebView == WebView; // Add Property Listener [WebView addobserver:self Forkeypath:@ "estimatedprogress" options: Nskeyvalueobservingoptionnew Context:nil];
After the monitoring of the property is added, the next step is to implement the progress bar, where the Calayer implicit animation
is used.
// progress bar UIView * progress = [[UIView Alloc] Initwithframe:cgrectmake (0 , 64 , Cgrectgetwidth (self.view.frame), 3 )]; Progress.backgroundcolor = [Uicolor Clearcolor];
[Self.view addsubview:progress]; // implicit animation Calayer * Layer = [calayer layer];layer.frame = CGRectMake (0 , 0 , 0 , 3 = [Uicolor Bluecolor]. Cgcolor; [Progress.layer addsublayer:layer];self.progresslayer = layer;
[WebView loadrequest:[nsurlrequest requestwithurl:[nsurl urlwithstring:@ "https://www.baidu.com"]
After doing this basic work, it is the most important way to listen to properties.
- (void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID)ObjectChange: (Nsdictionary<nskeyvaluechangekey,ID> *) Change context: (void*) context{if([KeyPath isequaltostring:@"estimatedprogress"]) {NSLog (@"Change = =%@", change); Self.progressLayer.opacity=1; Self.progressLayer.frame= CGRectMake (0,0, Self.view.bounds.size.width * [Change[nskeyvaluechangenewkey] floatvalue],3); if([Change[nskeyvaluechangenewkey] floatvalue] = =1) {Dispatch_after (Dispatch_time (Dispatch_time_now, (int64_t) (.2* nsec_per_sec)), Dispatch_get_main_queue (), ^{self.progressLayer.opacity=0; }); Dispatch_after (Dispatch_time (Dispatch_time_now, (int64_t) (.8* nsec_per_sec)), Dispatch_get_main_queue (), ^{self.progressLayer.frame= CGRectMake (0,0,0,3); }); } }Else{[Super Observevalueforkeypath:keypath Ofobject:ObjectChange:change Context:context]; }}
That's the main code, huh? Finally, don't forget to cancel the monitor.
-(void) dealloc { [Self.webview removeobserver:self forkeypath:@ " Estimatedprogress"];}
The above is the way to add a progress bar to Wkwebview. Finally attach the implementation of the Demo:https://github.com/wanliju/wlwkwebviewwithprogressline
Ios-webview (Wkwebview) Progress bar