UIwebView偏移设置问题

时间:2009-09-16 07:21:11

标签: iphone uiwebview

我正在使用UIWebView(加载了HTML文件),我想要滚动位置的偏移量,如果我改变文本大小,偏移应该保持不变。我想存储先前滚动的位置,即使我改变了字体大小 。如果这样做????

3 个答案:

答案 0 :(得分:3)

获取当前的偏移量:

int pageYOffset = [[webView stringByEvaluatingJavaScriptFromString:@"window.pageYOffset"] intValue];

设置页面偏移量使用:

    [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.body.scrollTop = %d", 100]];

答案 1 :(得分:2)

我在http://www.alexnking.com/2008/10/14/going-back-to-the-last-place-you-were-in-a-uiwebview/找到了另一种方法,当您想手动滚动UIWebView时,这可能会有很大的帮助。

获取当前滚动位置(垂直):

[myWebView stringByEvaluatingJavaScriptFromString: @"scrollY"];

// Application is terminating.

- (void)applicationWillTerminate:(UIApplication *)application {

  [[NSUserDefaults standardUserDefaults] setInteger:
    [[myWebView stringByEvaluatingJavaScriptFromString: @"scrollY"]
      intValue] forKey: @"currentScroll"];
}

// Application is loading.

- (void)applicationDidFinishLaunching:(UIApplication *)application {

 initialScrollPosition = [[NSUserDefaults standardUserDefaults]
                                integerForKey: @"currentScroll"];
}

// WebView is finished loading

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

  // Check if we need to scroll this somewhere.

  if (initialScrollPosition != 0) {

    // Scroll to the position.

    [passageView stringByEvaluatingJavaScriptFromString:
      [NSString stringWithFormat: @"window.scrollTo(0, %d);",
      self.initialScrollPosition]]; 

    // Set the initial scroll value to zero so we don't try

    // to scroll to it again if the user navigates to another page.

    self.initialScrollPosition = 0;

  }

}

答案 2 :(得分:1)

获取页面的总可滚动高度

int scrollHeight = [[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.scrollHeight"] intValue];