fer*_*tar 6 javascript iphone objective-c uiwebview
在UITextView中,我可以将控件的高度调整为其内容,如下所示:
CGRect frame = textView.frame;
frame.size.height = textView.contentSize.height;
textView.frame = frame;
Run Code Online (Sandbox Code Playgroud)
但我想使用UIWebView来显示富文本.UIWebVie的内容是:
NSString *myDescriptionHTML = [NSString stringWithFormat:@"<html> \n"
"<head> \n"
"<style type=\"text/css\"> \n"
"body {font-family: \"%@\"; font-size: %@; }\n"
"</style> \n"
"</head> \n"
"<body>%@</body> \n"
"</html>", @"helvetica",
[NSNumber numberWithInt:12], @"yadayadayada..."];
[webView loadHTMLString:myDescriptionHTML baseURL:nil];
Run Code Online (Sandbox Code Playgroud)
所以UIWebView只包含纯文本.如何实现类似于上述UITextView代码的结果?
fer*_*tar 14
虽然理论上提供了JavaScript方法
- (void)webViewDidFinishLoad:(UIWebView *)webview
CGRect oldBounds = [[self webview] bounds];
CGFloat height = [[webview stringByEvaluatingJavaScriptFromString:@"document.height"] floatValue];
[webview setBounds:CGRectMake(oldBounds.x, oldBounds.y, oldBounds.width, height)];
}
Run Code Online (Sandbox Code Playgroud)
应该工作(似乎适用于大多数人),它只是不适合我.我尝试了一些变化,它总是返回一个与真实内容的高度无关的大小.例如,一个衬垫将具有260或244高度.不知道为什么(很想知道).
所以我最后在这个答案中暗示:
- (void)webViewDidFinishLoad:(UIWebView *)aWebView {
CGRect frame = aWebView.frame;
frame.size.height = 1;
aWebView.frame = frame;
CGSize fittingSize = [aWebView sizeThatFits:CGSizeZero];
frame.size = fittingSize;
aWebView.frame = frame;
NSLog(@"size: %f, %f", fittingSize.width, fittingSize.height);
}
Run Code Online (Sandbox Code Playgroud)
我认为JS方式更优雅但是地狱,它不适合我,也无法弄清楚为什么,虽然这种方法开箱即用.