UIScrollView Setting contentoffset in viewwillappear not working

孤人 提交于 2019-12-23 12:22:13

问题


I was wondering if it is possible to set contentoffset for uiscrollview in viewwillappear method.

-(void) viewWillAppear:(BOOL)animated{

    [self.scrollView setContentOffset:CGPointMake(320, 0) animated:YES];
    NSLog(@"CALLED");    
}

I can see viewwillappear is running but unfortunately it is not setting offset.

Thank you


回答1:


you should call [super viewWillAppear:animated]; before attempting to set the offset.

However, it is possible you are trying to set the offset too early in the view lifecycle.

it might be good to override -(void)viewDidLayoutSubviews;, and set the offset there.

as your view's frames should all be set appropriately by that time. (remember to call super there too)




回答2:


I have an alternative option that should work better:

Instead of overriding viewDidLayoutSubviews, you can manually set the layout:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    view.layoutIfNeeded()
    // Do something here
}

This way you get a fresh layout that should match your expectation




回答3:


I have tested with your scrollView's contentSize & contentOffset in viewWillAppear. It is working fine to me. So, Please check weather your scrollView object is properly bound to your scrollView or not.



来源:https://stackoverflow.com/questions/25916000/uiscrollview-setting-contentoffset-in-viewwillappear-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!