Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resize WebView according to its content?

Tags:

cocoa

webview

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

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

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

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?

Thanks,

Miraaj

like image 446
Miraaj Avatar asked Apr 20 '10 13:04

Miraaj


1 Answers

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.

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));
    }
}
like image 168
Rob Keniger Avatar answered Oct 11 '22 17:10

Rob Keniger