tags:

views:

501

answers:

1

Hi all,

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

+1  A: 

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));
    }
}
Rob Keniger
Thanx Rob... I have implemented it and it is working fine.. but there is one problem: it is always setting the highest height for the webview which I am getting for different contents.. ie. if height was 1029.0 and now it should be 339.0 then it is appending space at end and showing web view with height 1029.0
Miraaj
Rob the problem is now resolved .. before setting its contents I am now resizing web view to some default and smaller values... say, (15.0, 0.0, 560.0, 10.0).. I must say Rob Rocks!
Miraaj