据我所知,您有一个包含自定义视图的窗口,它本身包含一个 Web 视图。
您希望将内容加载到 Web 视图中并让 Web 视图的框架更改大小以适应该内容。您还希望包含视图和窗口相应地调整大小。
一旦您知道如何根据其内容调整 Web 视图的大小,正如我对另一个问题的回答中所解释的那样,您就可以轻松地相应地调整容器的大小。
我将在这里重复我的答案,并添加调整包含对象的大小。
正如我在另一个答案中所指出的,您无法提前知道内容有多大,而且许多网站太大而无法显示在屏幕上。您可能需要将窗口的高度限制为屏幕高度才能使用。
- (void)loadWebPage
{
//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 difference from the old frame to the new frame
CGFloat deltaX = NSWidth(webFrameRect) - NSWidth(webViewRect);
CGFloat deltaY = NSHeight(webFrameRect) - NSHeight(webViewRect);
//make sure our web view and its superview resize automatically when the
//window resizes
[webView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
[[webView superview] setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
//set the window's frame, adjusted by our deltas
//you should probably add some code to constrain the size of the window
//to the screen's content size
NSRect windowFrame = window.frame;
[webView setFrameSize:NSMakeSize(NSWidth(window.frame) + deltaX, NSHeight(window.frame) + deltaY)];
//turn scroll bars back on
[[[webView mainFrame] frameView] setAllowsScrolling:YES];
}
}