如何根据其内容调整 WebView 的大小? [英] How to resize WebView according to its content?

查看:23
本文介绍了如何根据其内容调整 WebView 的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Web 视图中设置简单的 html 内容,然后根据其内容调整其大小.

I want to set simple html contents within a web view and then resize it according to its content.

为了在 web 视图中设置简单的 html 内容,我使用了这个代码并且它工作正常:

To set simple html contents within web view I used this code and it is working fine:

[[myWebView mainFrame] loadHTMLString:webViewContents baseURL:baseURLFramed];

现在,如果内容大于其实际大小,则它会出现在 Web 视图中,同时显示其中的垂直和水平滚动条.我想设置一些默认宽度并根据其内容管理高度,以便不会出现水平和垂直滚动条.

Right now, if content is more than its actual size then it appears in web view showing both vertical and horizontal scroller in it. I want to set some default width and manage height according to its content in a way so that neither horizontal nor vertical scroller appears.

谁能建议我一些解决方案?

Can anyone suggest me some solution for it?

谢谢,

米拉吉

推荐答案

你可以注册为 WebView 的框架加载委托,当页面加载时你可以询问主框架的文档视图它的大小并调整 WebView 的大小.确保关闭框架上的滚动条,否则会出现问题.

You can register as the WebView's frame load delegate, and when the page loads you can ask the main frame's document view for its size and resize the WebView. Make sure you turn off scrollbars on the frame or you will have problems.

请注意,某些页面可能非常大,当我测试 daringfireball.net 时,它的最高点为 17612,这显然太大而无法在屏幕上显示.

Be aware that certain pages can be very large, when I tested daringfireball.net it came in at 17612 points high, which is obviously too large to display on-screen.

- (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));
    }
}

这篇关于如何根据其内容调整 WebView 的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆