简体   繁体   English

iOS stringByEvaluatingJavaScriptFromString问题

[英]iOS stringByEvaluatingJavaScriptFromString issue

I have this code below that setup my UIWebView: 我在下面的代码中设置了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). 我为具有id的对象设置了新图像(它可以工作)。 But the size does not change. 但是大小不会改变。 As you can see I print height value using NSLog, but it shows 0.0000 for height. 如您所见,我使用NSLog打印高度值,但高度显示为0.0000。

This my HTML file: 这是我的HTML文件:

<!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. 所以我的问题是为什么当我调用stringByEvaluatingJavaScriptFromString时文档和img的高度不会改变。 Maybe do I need to create some reload method? 也许我需要创建一些重载方法?

You are accessing the height and width immediately after setting the src attribute. 设置src属性后,您将立即访问高度和宽度。 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. 您可以通过在以下委托调用中检查请求URL来检测是否正在加载图像。

- (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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM