Alexyuiop
Alexyuiop

Reputation: 823

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 here enter 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];
}

Upvotes: 5

Views: 4254

Answers (3)

Ned
Ned

Reputation: 1378

At first I used your answer) But after some time I found the solution how to fix this problem without scrolling each time content to the top. Hope it will work for you)

https://stackoverflow.com/a/22699785/246598

Upvotes: 1

Alexyuiop
Alexyuiop

Reputation: 823

I solved the problem

-(void)viewWillAppear:(BOOL)animated{

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

}

Upvotes: 4

Jsdodgers
Jsdodgers

Reputation: 5302

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).

Upvotes: 3

Related Questions