/////////////////////////////Initialize, Self.view is the parent control/////////////////////////////////_webview = [[UIWebView alloc] Initwithframe:cgrectmake (0,0, Self.view.frame.size.width,0)]; _webview.Delegate=Self ; _webview.scrollview.bounces=NO; _webview.scrollview.showshorizontalscrollindicator=NO; _webview.scrollview.scrollenabled=NO; [_webview SizeToFit];
///////////////////////////////set content, where a layer of div is used to get the actual height of the content (pixels), htmlcontent is a string in HTML format//////////////NSString * htmlcontent = [NSString stringWithFormat:@"<div id=\"Webview_content_wrapper\">%@</div>", htmlcontent]; [_webview loadhtmlstring:htmlcontent Baseurl:nil];
////////////////////////////////Delegate method overload////////////////////////////////////////////- (void) Webviewdidfinishload: (UIWebView *) webview{//Get page height (in pixels)NSString * Clientheight_str = [WebView stringbyevaluatingjavascriptfromstring:@"Document.body.offsetHeight"]; floatClientHeight =[Clientheight_str Floatvalue]; //set to WebViewWebview.frame = CGRectMake (0,0, Self.view.frame.size.width, clientheight); //Get webview Best Size (point)Cgsize frame =[WebView sizeThatFits:webView.frame.size]; //Get content actual height (pixels)NSString * height_str= [WebView stringbyevaluatingjavascriptfromstring:@"document.getElementById (' Webview_content_wrapper '). offsetheight + parseint (window.getComputedStyle ( document.getElementsByTagName (' body ') [0]). GetPropertyValue (' margin-top ') + parseint (window.getComputedStyle ( document.getElementsByTagName (' body ') [0]). GetPropertyValue (' Margin-bottom '))"]; floatHeight =[Height_str Floatvalue]; //content actual height (pixels) * point and pixel ratioHeight = height * Frame.height/clientheight; //Set WebView height again (point)Webview.frame = CGRectMake (0,0, self.view.frame.size.width, height);}
Perfect solution--ios WebView self-adapting content height