开发者

How do I make UIWebView scroll to the top?

Is there a way to make 开发者_如何学运维a UIWebView scroll to the top when I touch say a UISearchView within the same viewController (without using Javascript).

Something like this:

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
      [myWebView scrollToTop];    //pseudocode 

}

In other words, what happens when I touch the top bar can also happen programmatically.


CGPoint top = CGPointMake(0, 0); // can also use CGPointZero here
[myWebView.scrollView setContentOffset:top animated:YES];

(Note that if you have set myWebView.scrollView.contentInset.top you will want to take that into account instead of just scrolling to CGPointZero.)


Here's a really ugly, terrible way to do this. I'm answering this to show you what never to do.

for (UIView *subview in webView.subviews)
{
    if ([subview isKindOfClass:[UIScrollView class]])
        [(UIScrollView*)subview setContentOffset:CGPointZero animated:YES];
}


If you don't want to use JavaScript there's no public API method to do this. UIWebViews don't inherit from scroll views, so you can't use any of the usual methods. As you've figured out, it's possible to do with JavaScript. You can try to find the actual scroll view in the UIWebView, but it's all undocumented and not really a good thing to do in a production app.

Update - as of iOS 5 you can now get direct access to a web view's UIScrollView - see Reconquistador's answer for more information.


Scroll the UIWebView by calling JavaScript through Objective-C:

NSString *script = @"scrollTo(0, 0)";
[webView stringByEvaluatingJavaScriptFromString:script];

For smooth scrolling, use a library like jQuery:

NSString *script = @"$('html, body').animate({scrollTop:0}, 'slow')";
[webView stringByEvaluatingJavaScriptFromString:script];


Access the UIWebView's scrollview and set YES to method scrollsToTop;

WebView.scrollView.scrollsToTop = YES;

Hope this helps!


Swift 3.x

webView.scrollView.setContentOffset(CGPoint.zero, animated: true)


I don't believe you will find any officially supported method to do what you are wanting.


This works for me:

CGPoint topOffset = CGPointMake(0, 0);
//[scrollView setContentOffset: topOffset animated: YES];
[[[webView subviews] lastObject] setContentOffset:topOffset animated:YES];

Where webView is the subclass of the UIWebView, of course.


why not just touch the status bar of your device. for all the scrollView based controls, tableView, webView, scrollView, there is a : The scroll-to-top gesture is a tap on the status bar; when this property is YES, the scroll view jumps to the top of the content when this gesture occurs. The default value of this property is YES.


Displaying a PDF in a UIWebView, I found you can jump to the top simply by reloading the document.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜