如果animated = NO,则setContentOffset: animated:不会有任何效果。

3
我正在尝试在 webView 中查看的 PDF 中滚动到上次查看的位置。当卸载 PDF 时,它将保存 webView 的 scrollView 的 Y 偏移量。然后,当重新打开 PDF 时,我想跳转到他们离开的位置。
以下代码在将 animated 设置为 YES 时工作正常,但是当设置为 NO 时,不会发生任何事情。
    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));

这将输出:

滚动到 5432.000000

CO:{0, 5432}

然而,PDF 仍然显示顶部页面。

我查看了类似问题的答案,但它们并没有解决这个问题。

谢谢您的帮助 :)


你尝试过调用 setNeedsDisplay 吗?这只是一个想法。或者你可以将偏移量设置为比所需位置少一个像素,然后不使用动画将其移动到所需位置,最后再使用动画将其移动一个像素。这样行吗? - James
1个回答

1

UIWebView 组件渲染 PDF 之前,您无法触及 contentOffset。对于 setContentOffset: animated:YES,它可以工作是因为动画会强制进行渲染。

如果您在渲染开始后至少等待 0.3 秒(根据我的测试),那么就没有任何问题了。

例如,如果您在 UIViewControllerviewDidLoad 中加载 PDF,则可以在 viewDidAppear: 中使用 performSelector:withObject:afterDelay: 来延迟设置 contentOffset

为了在设置 contentOffset 之前隐藏 PDF,您可以将其 alpha 设置为 0.01(除非渲染不会开始,否则不要将其设置为 0),并在设置完 contentOffset 后将其设置回 1。

@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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接