如何根据其内容调整WebView的大小?
我想在web视图中设置简单的html内容,然后根据其内容调整它的大小。如何根据其内容调整WebView的大小?
要设置我用这个代码的Web视图中简单的HTML内容,并将其工作正常:眼下
[[myWebView mainFrame] loadHTMLString:webViewContents baseURL:baseURLFramed];
,如果含量大于它的实际大小,然后它出现在Web视图显示垂直和水平卷轴在它。我想设置一些默认宽度和管理高度根据其内容的方式,使横向和纵向滚动不出现。
任何人都可以为我提供一些解决方案吗?
感谢,
Miraaj
可以作为WebView
的框架装载委托登记,并在页面加载时,你可以问主框架的文档视图,其规模和调整WebView
。确保关闭框架上的滚动条,否则会出现问题。
请注意,某些页面可能非常大,当我测试daringfireball.net时,它以17612点的高度显示,这显然太大而无法在屏幕上显示。
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
//set ourselves as the frame load delegate so we know when the window loads
[webView setFrameLoadDelegate:self];
//turn off scrollbars in the frame
[[[webView mainFrame] frameView] setAllowsScrolling:NO];
//load the page
NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://daringfireball.net"]];
[[webView mainFrame] loadRequest:request];
}
//called when the frame finishes loading
- (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)webFrame
{
if([webFrame isEqual:[webView mainFrame]])
{
//get the rect for the rendered frame
NSRect webFrameRect = [[[webFrame frameView] documentView] frame];
//get the rect of the current webview
NSRect webViewRect = [webView frame];
//calculate the new frame
NSRect newWebViewRect = NSMakeRect(webViewRect.origin.x,
webViewRect.origin.y - (NSHeight(webFrameRect) - NSHeight(webViewRect)),
NSWidth(webViewRect),
NSHeight(webFrameRect));
//set the frame
[webView setFrame:newWebViewRect];
//NSLog(@"The dimensions of the page are: %@",NSStringFromRect(webFrameRect));
}
}
另一种选择是向DOM询问您的内容的高度。
- (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
{
NSString* heightOutput = [sender stringByEvaluatingJavaScriptFromString:@"document.getElementById(\"foo\").scrollHeight;"];
NSInteger height = [heightOutput integerValue];
[[self splitView] setPosition:height + 10 ofDividerAtIndex:0];
}
这里的关键在于将您的内容放入指定元素中,以便可以使用getElementById。我的实现使用了一个简单的<div id="foo">
元素。
在我的特殊情况下,我的WebView是在NSSplitView的内部,所以首先将WebView的高度重新设置为小,导致闪烁。
我有一个示例项目here演示它。
这对我来说比'[[[webFrame frameView] documentView] frame]'更好,因为它总是返回适当的值。我不知道为什么,但'documentView.frame'只有在第一次加载页面时才起作用,否则它会返回空白大小(可能是因为缓存)。 – Darrarski 2013-12-03 14:23:54
事实上,@Darrarski - 这甚至可以在调整gor大小后重新调整帧的大小,即宽度发生了变化,导致内容高度发生变化,而接受的答案在这种情况下无法帮助,因为它会不断报告初始大小。 – 2018-01-09 08:40:07
Thanx Rob ...我已经实现了它,它工作正常..但有一个问题:它总是设置最高的webview,我得到不同的内容的高度..即。如果高度是1029.0,现在它应该是339.0,那么它是在末尾追加空格,并显示高度的web视图1029.0 – Miraaj 2010-04-21 07:16:10
Rob现在解决了问题。在设置其内容之前,我现在将web视图的大小调整为某些默认值和较小的值。 ..说,(15.0,0.0,560.0,10.0)..我必须说罗布岩! – Miraaj 2010-04-21 10:29:04
当我在WebView中的某些交互过程中更改DOM时,会触发更改其可见区域的尺寸,此方法“webView:didFinishLoadForFrame”将不会再次调用,是true?在这种情况下是否会有一些代表被调用?顺便说一句:你的解决方案不适合我。也许你可以帮忙[这里](http://*.com/q/21992854/1146700)? – beipawel 2014-02-24 16:20:45