UIScrollView does not restore properly

2019-06-02 11:26发布

问题:

I have a Scrollview, it's properties are set in viewDidAppear. Now when I get to the Scrollview first time there isn't any problem. However I have buttons that are assigned to UINavigationController. So when I press into one of them UINavigationController opens up, when I close the navigation controller, ScrollView does not restore properly. It basically aligns the centre of the screen as previously pressed button location. So if I try to scroll up it does not.

I have tried using this in my viewDidAppear:

scrollView.center = CGPointMake(scrollView.contentOffset.x, scrollView.contentOffset.y); 

Which did not quite work. How can I solve this? I am using iOS6.1

回答1:

Actually I found the answer here:

UIScrollview Autolayout Issue

The exact code that I used is:

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    //save the current offset
    previousPoint = scrollView.contentOffset;
    //set current view to the beginning point
    self.scrollView.contentOffset = CGPointZero;
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    //retrieve the previous offset
    self.scrollView.contentOffset = previousPoint;
}

previousPoint is nothing but a CGPoint variable declared on the implementation.



回答2:

I've had this problem before too. This answer shows how to overcome this issue.

Basically, you need to set the scrollview's contentOffset appropriately in viewWillAppear: and viewDidDisappear:.

EDIT: Here's another related question that you might find useful, UIScrollview Autolayout Issue.