We develop the details page, sometimes we need to calculate the height of webview or Wkwebview, then calculate the height of ScrollView and put WebView on ScrollView. But the calculation of the webview height of the process is time-consuming, because the following agent, the Web page thoroughly loaded to calculate the height, we need to calculate the height first, the page appears first text, as for the picture of the page, you can slowly cache the full display. This does not screen time too long.
-(void) WebView: (Wkwebview *) WebView didfinishnavigation: (null_unspecified wknavigation *) navigation
{
/** Calculation Height *
Dispatch_async (Dispatch_get_global_queue (0,0), ^{
[_webview evaluatejavascript:@ "Document.documentElement.offsetHeight" completionhandler:^ (id_nullable result, Nserror *_nullable error) {
Get WebView Height
CGRect frame = _webview.frame;
Frame.size.height = [result doublevalue] + 50;
_webview.frame = frame;
_scrollviewheight = _webview.height +;
_scrollview.contentsize = Cgsizemake (Kscreenwidth, _scrollviewheight);
}];
});
}
Note: The above agent is abandoned by the landlord, too time-consuming. Instead, use the following method: (illustrated by the Wkwebview)
Step One: Add observers
[_webview.scrollviewaddobserver:selfforkeypath:@ "Contentsize" options:NSKeyValueObservingOptionNewcontext:nil];
Step TWO: The Observer listens to the contentsize changes of WebView
-(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID) object change: (nsdictionary *) Change context: (void *) Context {
if ([keypathisequaltostring:@ "Contentsize"]) {
Dispatch_async (Dispatch_get_global_queue (0,0), ^{
Document.documentElement.scrollHeight
Document.body.offsetHeight
[_webviewevaluatejavascript:@ "Document.documentElement.offsetHeight" completionhandler:^ (id_nullable result, Nserror * _nullable error) {
CGRect frame =_webview.frame;
Frame.size.height = [Resultdoublevalue] + 50;
_webview.frame = frame;
_scrollviewheight =220 + _webview.height;
_scrollview.contentsize =cgsizemake (kscreenwidth,_scrollviewheight);
}];
});
}
}
Step three: Remove the Observer
-(void) dealloc
{
[_webview.scrollviewremoveobserver:selfforkeypath:@ "Contentsize"];
}
Summary: The above method can not be said to be particularly fast loading, but at my speed at least a few times increased. I am also looking for better optimization methods, such as caching and so on. There are better ways to know the small partners, welcome to post, landlord grateful ...