views:

703

answers:

1

Hello,

I'm using UIWebView to display article and one of functionality requirements is text resizing. Since, setting increased size and reloading UIWebView loses scroll offset I decided use Javascript solution.

Article HTML body tag looks like this: <body style='font-size:12px;'>

And resizing function basically looks like this:

NSString * str;

str = [NSString stringWithFormat:@"document.getElementsByTagName('body')[0].style.fontSize=%d;", app.storyTextSize];

[textView stringByEvaluatingJavaScriptFromString:str];

[textView stringByEvaluatingJavaScriptFromString:str];

And as a matter of fact it works. In my iPod it works great (double stringByEvaluatingJavascript does the trick), but I have reports from other tester that in his iPhone sometimes it works and sometimes it doesn't (I guess what he meant by that is that not every button click executes Javascript properly even if it should be executed twice for reassurance).

Is there any way I could optimize my solution and make it more bullet proof? Or maybe there is a way to scroll back to previous position after reloading UIWebView, but, once again, setting offset in UIWebView will be Javascript bussiness..

+1  A: 

Isn't the "sometimes it works, sometimes not" linked to the fact that sometimes the javascript is invoked before the HTML page is fully loaded, sometimes after the full load ?

yonel
That's a good observation, but I doubt it's the case here since I construct all HTML in code and then pass to UIWebView. Then only thing that could take a while to load (especially on 3G) is external <img/>, but can it be the problem?
sniurkst
I think that the best way to check if the loading of the page does not impact the behavior of the JS invokation is to implement the UIWebViewDelegate protocol and check that the javascript is called only once the - (void)webViewDidFinishLoad:(UIWebView *)webView is called : when this callback is called, you're sure that the state of the webview is "stable".
yonel
I just tested application with onLoad alert and slowed internet connection - you were right! JavaScript can not be called until all external images are fully loaded. Thanks for pointing the right path :)
sniurkst