Skip to content

Instantly share code, notes, and snippets.

@paingpyi
Created May 29, 2013 14:17
Show Gist options
  • Save paingpyi/5670599 to your computer and use it in GitHub Desktop.
Save paingpyi/5670599 to your computer and use it in GitHub Desktop.
How to Synchronously get the Height of UIWebView
- (UIWebView*)createWebViewContent:(NSString*)content frame:(CGRect)frame
{
NSString * webContent = [NSString stringWithFormat:@"<html><head><meta name = \"viewport\" content = \"initial-scale = 1.0, user-scalable = no\"><style type='text/css'> body {color:black; margin:0 0 0 7pt; font-family: %@ !important; font-size:13; background-color: transparent;} .label{color:red} </style></head><body face=\"Bookman Old Style, Book Antiqua, Garamond\" size=\"5\"><div>%@</div></body></html>",WEBVIEW_FONT,content];
UIWebView *webView = [[UIWebView alloc] initWithFrame:frame];
webView.delegate = self;
webView.tag = 444;
webView.backgroundColor = [UIColor clearColor];
[webView loadHTMLString:webContent baseURL:nil];
NSLog(@"before CFRunLoop");
CFRunLoopRunInMode((CFStringRef)NSDefaultRunLoopMode, 1, NO);
NSLog(@"after CFRunLoop");
[self waitHtmlLoadingTime:webView];
return webView;
}
- (void) waitHtmlLoadingTime:(UIWebView*)webView
{
float webViewHeight = 30;
webViewHeight = [[webView stringByEvaluatingJavaScriptFromString: @"document.body.offsetHeight"] floatValue];
NSLog(@"webViewHeight - %f",webViewHeight);
CGRect size = webView.frame;
size.size.height = webViewHeight;
webView.frame = size;
}
-(void) stopRunLoop
{
CFRunLoopRef runLoop = [[NSRunLoop currentRunLoop] getCFRunLoop];
CFRunLoopStop(runLoop);
}
-(void) webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
NSLog(@"before didFailLoadWithError");
[self performSelector:@selector(stopRunLoop) withObject:nil afterDelay:.01];
}
-(void) webViewDidFinishLoad:(UIWebView *)webView
{
NSLog(@"before webViewDidFinishLoad");
[self performSelector:@selector(stopRunLoop) withObject:nil afterDelay:.01];
}
@paingpyi
Copy link
Author

@samuelbezerrab
Copy link

It helped me. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment