1
votes

I have this code below that setup my UIWebView:

- (void)webViewDidFinishLoad:(UIWebView *)webView
{

    [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementById(\"image\").src=\"q%@.png\";", self.imageIndex]];

    NSLog(@"%f", [[webView stringByEvaluatingJavaScriptFromString:@"document.getElementById(\"image\").height;"] floatValue]);

    CGFloat width = [[webView stringByEvaluatingJavaScriptFromString:@"document.width"] floatValue];
    CGFloat height = [[webView stringByEvaluatingJavaScriptFromString:@"document.height"] floatValue];   


    CGSize contentSize = CGSizeMake(width, height);

    [self setUpNewSize:contentSize];
}

I set new image for object with id (and it works). But the size does not change. As you can see I print height value using NSLog, but it shows 0.0000 for height.

This my HTML file:

<!DOCTYPE html>
<html>
    <head>

        <title>Question 1</title>


    </head>

    <body>

        <h3 id="header">Question 1</h3>

        <img id="image" src="" alt="" width="100%">

    </body>

</html>

I have different height for each image and it changes dynamically. So my question is why the heights for document and img don't change when I call stringByEvaluatingJavaScriptFromString. Maybe do I need to create some reload method?

1

1 Answers

1
votes

You are accessing the height and width immediately after setting the src attribute. You should wait for the image to load first.

You can detect if the image is getting loaded by checking the request url in the following delegate call.

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

Once you know the image started loading, you can then get its height and width in the subsequent call to

- (void)webViewDidFinishLoad:(UIWebView *)webView