[英]WebView height not set based on its content
我知道这个问题已经发布了很多次,但是我仍然无法根据其内容更改UIWebView
的高度
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.title=@"webview";
[_webView setDelegate:self];
NSString * string = @"<h1>This is HTML string</h1>";
[_webView loadHTMLString:string baseURL:nil];
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
NSLog(@"start loadinng.......");
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSLog(@"finish loading.......");
CGRect frame = _webView.frame;
frame.size.height = 1;
_webView.frame = frame;
CGSize fittingSize = [_webView sizeThatFits:CGSizeZero];
frame.size = fittingSize;
_webView.frame = frame;
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
NSLog(@"Failed to load with error :%@",[error debugDescription]);
}
有人可以帮助我如何调整UIWebView
高度吗?
这是你的答案。
- (void)webViewDidFinishLoad:(UIWebView *)webView {
if (webView.isLoading){
return;
}
CGSize contentSize = webView.scrollView.contentSize;
NSLog (@"height: %f",contentSize.height);
}
达到此高度后,将webView重新设置为新的宽度和高度,并重新设置其父视图(如果有)。
这个怎么样。
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
[webView sizeToFit];
webView.frame = CGRectMake(x,y,width,webView.frame.size.height);
}
我通常使用以下方法来设置UIWebview框架的内容大小:
- (void)webViewDidStartLoad:(UIWebView *)webView
{
CGRect frame = webView.frame;
frame.size.height = 5.0f;
webView.frame = frame;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
CGSize mWebViewTextSize = [webView sizeThatFits:CGSizeMake(1.0f, 1.0f)]; // Pass about any size
CGRect mWebViewFrame = webView.frame;
mWebViewFrame.size.height = mWebViewTextSize.height;
webView.frame = mWebViewFrame;
//Disable bouncing in webview
for (id subview in webView.subviews)
{
if ([[subview class] isSubclassOfClass: [UIScrollView class]])
{
[subview setBounces:NO];
}
}
}
当WebView加载完其内容时,将自动调用它们(如果您将webviews委托设置为此类)。
要么
这可能会帮助您:)
First calculate height of web view for desired content.
NSString* lString = @"<h1>This is HTML string</h1>";
NSAttributedString* lAttributedText = [[NSAttributedString alloc] initWithData: [lString dataUsingEncoding:NSUTF8StringEncoding]
options:@{
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)
}
documentAttributes: nil
error:nil];
CGRect lBoundingRect = [lAttributedText boundingRectWithSize: CGSizeMake(_webView.bounds.size.width, CGFLOAT_MAX) options: NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading context: nil];
then set it to _webView.frame
Now, load web view
[_webView setDelegate:self];
[_webView loadHTMLString: lString baseURL:nil];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.