Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIScrollview shifting contents up after scrolling down and pushing new viewcontroler

I have trouble figuring out this issue on my uiscrollview. The contents inside my uiscrollview move up after clicking a button to push a new view controller onto the screen, and then going back to the original view controller. Notice how the the top of the scrollview changes.

enter image description hereenter image description here

Here is the code for the scrollView

- (void)viewDidLoad{
    [super viewDidLoad];

    [scroll setScrollEnabled:YES];
    [scroll setContentSize:CGSizeMake(923, 934)];
    [self.view addSubview:scroll];
}
like image 522
Alexyuiop Avatar asked Aug 08 '13 09:08

Alexyuiop


2 Answers

I solved the problem

-(void)viewWillAppear:(BOOL)animated{

     [scroll setContentOffset:CGPointMake(0,0)];

}
like image 60
Alexyuiop Avatar answered Sep 28 '22 09:09

Alexyuiop


I think this is because of the way that the autoLayout is done when creating views. For some reason when you first add a view to the screen (the scrollview), the view's coordinates don't include under the navigationbar, but after another view is added, they do. One way that I get around this is by creating a blank view and adding it as a subview before adding the scrollView.

Such as:

UIView *vi = [[UIView alloc] initWithFrame:CGRectMake(-10, -10, 1, 1)]
[vi setBackgroundColor:[UIColor clearColor]];
[self.view addSubview:vi];
//Then add scrollView

This just creates an offscreen 1x1 clear view and adds it to the main view which makes the main view properly locate itself before adding the scrollView.

You also might want to change the y coordinate of your scrollView, as doing this with your current code will make it always behave as in the second case.

I usually do:

frame.y+=self.navigationController.navigationBar.frame.size.height + 20;

which adds the navigation bar height and the status bar height (20).

like image 28
Jsdodgers Avatar answered Sep 28 '22 10:09

Jsdodgers