Karl Taylor
Karl Taylor

Reputation: 47

Programmatically scroll a UIWebView on iOS

How can I programmatically scroll a UIWebView in Objective-C (iOS)?

The only solution I can think of is to put it inside a UIScrollView and programmatically scroll that, however this presents the problem that the web view is often the wrong size and therefore the bottom of the page is cut off when scrolling. I have no idea how to programatically change the size of a web view to fit its content either... so far I have:

UIView *webDocView = webView.subviews.lastObject;
webView.frame = CGRectMake(webView.frame.origin.x, webView.frame.origin.y, webView.frame.size.width, webDocView.frame.size.height);

But for some reason this will not work.

Should I persue the solution of using a ScrollView... or is there a better way to do this?

Upvotes: 1

Views: 2635

Answers (3)

RawMean
RawMean

Reputation: 8735

Here is a simple solution that I've tested and it works:

Add the following in viewDidLoad to add a scrollView on top of our webView:

    self.scrollView = [[UIScrollView alloc] init];
self.scrollView.delegate = self;
[self.webView addSubview:self.scrollView];

When the page loads, we adjust the frame and contentSize of the scrollView

-(void) webViewDidFinishLoad:(UIWebView *)webView {
self.scrollView.frame = webView.bounds;
self.scrollView.contentSize = webView.scrollView.contentSize;
}

Now you can change offset of the web view.scrollView by setting self.webView.scrollView.contentOffset to whatever CGPoint that you want programatically.

Remember that, by doing this, touch events are no longer passed to the webiview. If you want the web view to still respond to the user dragging, then also do this:

#pragma mark UIScrollView Delegate
-(void) scrollViewDidScroll:(UIScrollView *)scrollView {
self.webView.scrollView.contentOffset = scrollView.contentOffset;
}

Upvotes: 0

Ken
Ken

Reputation: 31161

Apple says: "You should not embed UIWebView objects in UIScrollView object. If you do so, unexpected behavior can result because touch events for the two objects can be mixed up and wrongly handled." This probably has a lot to do with instances of both UIWebView and UIScrollView being scrollable and the interaction of two scrolling requests is too much.

Upvotes: 0

Chris Wagner
Chris Wagner

Reputation: 21003

UIWebView doesn't have any properties that specify its position on the document it is rendering. You likely need to do this through Javascript, if you want the animated feel of it take a look at this. http://www.learningjquery.com/2007/09/animated-scrolling-with-jquery-12

Upvotes: 4

Related Questions