rich
rich

Reputation: 2136

How to use injected JavaScript to scroll UIWebView to a point

I have been reading up on this all day and simply cannot solve the problem. I am attempting to load a web page and after it is done loading automatically scroll it to a pre determined point. I have been reading tutorials such as this http://iphoneincubator.com/blog/windows-views/how-to-inject-javascript-functions-into-a-uiwebview and still no luck.

Here is my .m where the problem is occurring. I'm desperate please help! Also, it is telling me that my webViewDidFinishLoad is overwriting the instance variable but that shouldn't be a problem I believe

- (void)viewDidLoad {
    [super viewDidLoad];

    NSString *urlAddress = @"http://www.twitter.com/richrines";
    NSURL *url = [NSURL URLWithString:urlAddress];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
    [webView loadRequest:requestObj];

    // Do any additional setup after loading the view from its nib.
}


- (void)webViewDidFinishLoad:(UIWebView *)webView {
     [webView stringByEvaluatingJavaScriptFromString:@"var script = document.createElement('script');"  
     "script.type = 'text/javascript';"  
     "script.text = \"function myFunction() { "  
     "window.scrollTo(100,100)"
     "}\";"  
     "document.getElementsByTagName('head')[0].appendChild(script);"];  

     [webView stringByEvaluatingJavaScriptFromString:@"myFunction();"];
}

Upvotes: 7

Views: 2698

Answers (3)

OscarWyck
OscarWyck

Reputation: 2535

This is works perfectly for me, but includes no javascript:

Make sure you set the view controller where you have your web view to be a UIWebViewDelegate, and declare this in the @interface of the header file (.h).

[yourWebView setDelegate:self];


Then, in the webViewDidFinishLoad: method, insert this code:

[yourWebView.scrollView scrollRectToVisible:CGRectMake(0, yourWebView.bounds.size.height + 100, 1, 1) animated:NO];           

Upvotes: 0

Jon Conner
Jon Conner

Reputation: 157

Couldn't you change the offset in the webView's scrollView property?

[webView.scrollView setContentOffset:CGPointMake(100, 100)];

Upvotes: -1

Anomie
Anomie

Reputation: 94794

Why are you doing it in such a complicated manner? This should be all you need:

[webView stringByEvaluatingJavaScriptFromString:@"window.scrollTo(100,100)"];

Upvotes: 3

Related Questions