Brodie
Brodie

Reputation: 3506

setContentOffset: animated: wont do anything if animated = NO

I'm trying to scroll to the last viewed position of a PDF that's being viewed in a webView. When the PDF is unloaded, it will save the y offset of the webView's scrollView. Then when the PDF is re-opened, I would like to jump to where they left off.

The below code works fine when animated is set to YES, however when it's set to NO, nothing happens

    float scrollPos = [[settingsData objectForKey:kSettingsScrollPosition]floatValue];
    NSLog(@"scrolling to %f",scrollPos);
    [webView.scrollView setContentOffset:CGPointMake(0, scrollPos) animated:NO];
    NSLog(@"ContentOffset:%@",NSStringFromCGPoint(webView.scrollView.contentOffset));

this outputs:

scrolling to 5432.000000

CO:{0, 5432}

However the PDF is still displaying the top page

I have viewed the answers on similar questions here but they dont solve this problem.

Thanks for the help :)

Upvotes: 3

Views: 1528

Answers (1)

Damien Debin
Damien Debin

Reputation: 2822

You can't touch contentOffset before UIWebView component has done the rendering of the PDF. It works for setContentOffset: animated:YES because the animation forces the rendering.

If you set contentOffset to at least 0.3s (from my test) after the rendering starts, there is no problem at all.

For instance if you load the PDF in the viewDidLoad of your UIViewController you can use performSelector:withObject:afterDelay: in your viewDidAppear: to delay contentOffset setting.

To hide the PDF before contentOffset is set, you can set its alpha to 0.01 (don't set it to 0 unless rendering would not start) and set it back to 1 after you set contentOffset.

@interface ViewController : UIViewController
{
    UIWebView *w;
}

@property (nonatomic, retain) IBOutlet UIWebView *w;

@end

@implementation ViewController

@synthesize w;

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSURL *u = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"pdf"];
    [w loadRequest:[NSURLRequest requestWithURL:u]];
    w.alpha = 0.01f;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self performSelector:@selector(adjust) withObject:nil afterDelay:0.5f];
}

- (void)adjust
{
    float scrollPos = 800;
    NSLog(@"scrolling to %f",scrollPos);
    [w.scrollView setContentOffset:CGPointMake(0, scrollPos) animated:NO];
    NSLog(@"ContentOffset:%@", NSStringFromCGPoint(w.scrollView.contentOffset));
    w.alpha = 1;
}

@end

Upvotes: 1

Related Questions