如何确定stringByEvaluatingJavaScriptFromString评估过程完成?

时间:2013-08-08 11:24:52

标签: javascript ios objective-c uiwebview uiwebviewdelegate

我正在将html文件读入UIWebview。在webViewDidFinishLoad我正在做水平滚动的javascript函数。下面的代码工作正常。但我无法预测javascript函数何时完成。

在可见的webview中首先加载html文件,然后运行脚本。所以我可以确定webViewDidFinishLoad中的javascript结束。

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

    NSString *scriptString =@"javascript:function initialize() {  var eelam = document.getElementsByTagName('body')[0]; var ourH = window.innerHeight;var ourW = window.innerWidth;  var fullH = eelam.offsetHeight;  var pageCount = Math.ceil(fullH/ourH)+1; var padval = parseInt((screen.width*10)/100);var currentPage = 0; var newW = pageCount*ourW;eelam.style.height = (ourH - 30)+'px';eelam.style.width = (newW)+'px';eelam.style.webkitColumnGap = '5px'; eelam.style.margin = '25px'; eelam.style['margin-left']='2px';eelam.style.webkitColumnCount = pageCount; window.interface.setPageCount(pageCount);window.interface.setColumnWidth(screen.width);window.interface.setContent(eelam);window.interface.setColumnGap(padval);};";

    // set font
    NSString *jsString = [[NSString alloc] initWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '%d%%'",
                          textFontSize];

    [mywebview stringByEvaluatingJavaScriptFromString:scriptString];

    [mywebview stringByEvaluatingJavaScriptFromString:@"javascript:initialize()"];

    [mywebview stringByEvaluatingJavaScriptFromString:jsString];

    // scroll disable
    UIView* row = nil;
    for(row in webView.subviews){
        if([row isKindOfClass:[UIScrollView class] ]){
            UIScrollView* scrollRow = (UIScrollView*) row;
            scrollRow.scrollEnabled = NO;
            scrollRow.bounces = NO;
            scrollRow.pagingEnabled=YES;
        }
    }

// this code is also not use to handle my issue
if ([[mywebview stringByEvaluatingJavaScriptFromString:@"document.readyState"] isEqualToString:@"complete"]) {

       }


}

请告诉我,

提前感谢,

2 个答案:

答案 0 :(得分:1)

该功能不是异步的。它在从评估函数返回值之前完成。

答案 1 :(得分:1)

“stringByEvaluatingJavaScriptFromString”是一个同步函数,一旦javascript完成执行,则返回回调。

但是,您可以通过使javascript以异步方式运行来使其异步

示例:[mywebview stringByEvaluatingJavaScriptFromString:@“javascript:initialize()”];

在Javascript中写一个函数

function initialize(){ setTimeout(function(){// init},0);

使用此线程,您的本机线程将为空,并将在3-4毫秒内立即返回

相关问题