Recently in the project need to add a WebView loaded page, the following is a list of the contents of this webview display, the list to be loaded according to the background of the HTML adaptive change height, TableView cell is displayed below the WebView, The effect shown
1. Set WebView, initial height set to 0.5, set to Tableheaderview as WebView, add an observer, monitor WebView contentsize changes
_mywebview = [[UIWebView alloc]initwithframe:cgrectmake (0, 0, Kscreenwidth, 0.5)]; _mywebview.delegate = self; _mywebview.scrollview.scrollenabled = NO; _mywebview.scrollview.showshorizontalscrollindicator = NO; [_mywebview SizeToFit]; _mywebview.scrollview.bounces = NO; [Self.myWebView.scrollView addobserver:self forkeypath:@ "contentsize" options:nskeyvalueobservingoptionnew context : nil]; _mytableview.tableheaderview = _mywebview;
2. In the Observer method, by acquiring the contents of the entire WebView, modify his frame
-(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID) object change: (nsdictionary *) Change context: (void *) context{ if ([KeyPath isequaltostring:@ "Contentsize"]) { WEBVIEWH = [[Self.mywebview stringbyevaluatingjavascriptfromstring:@ "Document.body.offsetHeight"] floatvalue]+15; CGRect newframe = self.myWebView.frame; NewFrame.size.height = WEBVIEWH; NSLog (@ "Present height ===%f", WEBVIEWH); Self.myWebView.frame = Newframe; Self.myTableView.tableHeaderView = Self.mywebview; }}
3. Finally, don't forget to release the Observer
-(void) dealloc{ [Self.myWebView.scrollView removeobserver:self forkeypath:@ "Contentsize"];}
Add Webview,webview Adaptive height to the headerview of TableView