alexeis
alexeis

Reputation: 2198

UIScrollView: Content first appears too low

Before posting a lot of code I want to ensure it's not a commonly known issue (independent of the specific code) so first I'll explain my problem in general:

In the storyboard I created a UIViewController, added a UIScrollView as well as another UIView (hierarchical subviews). I need the scroll view to push the content up when the keyboard appears so the textfield stays visible. When running the app everything works fine besides the fact, that the content appears closer to the bottom of the screen than defined in my storyboard. As soon as I tapped the textfield the content is scrolled up (by adjusting scrollView.contentInset and scrollView.scrollIndicatorInsets to (0.0, 0.0, keyboardSize!.height, 0.0)) and its position is like expected. When pressing the return key, the keyboard disappears, the content scrolls down again (by adjusting scrollView.contentInset and scrollView.scrollIndicatorInsets to (0.0, 0.0, 0.0, 0.0)) but now everything is like I want it to be and like it was defined in the storyboard.

Trying to understand what's happening I also let print out to the console some of the y points in viewDidLoad(), keyboardDidShow and keyBoardDidHide but when comparing those, they're all the same. What did I miss out? Do you need to see some specific part of my code?

enter image description here

enter image description here

Upvotes: 1

Views: 396

Answers (4)

Coruscate5
Coruscate5

Reputation: 2563

I just had this issue - I messed around with all the solutions above, finally found the fix.

For me, I just had to flip the right switch in the ViewController constructor:

public ViewController ()
{
    AutomaticallyAdjustsScrollViewInsets = false;
}

I'm suspecting the results would be similar for LoadView(), ViewWillAppear(), etc...

Upvotes: 1

alejandrormz
alejandrormz

Reputation: 597

This one will work even better, without visibly "bumping" the first item on the view, but doing so before it is shown to the user:

-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    scrollView.contentInset = UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0);
    scrollView.scrollIndicatorInsets = UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0);
}

Upvotes: 0

alexeis
alexeis

Reputation: 2198

It works as desired when setting up

viewDidAppear(animated: Bool) {
    scrollView.contentInset = UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0)
    scrollView.scrollIndicatorInsets = UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0)
}

Any comments concerning other/better solutions are welcome!

Upvotes: 3

Kamchatka
Kamchatka

Reputation: 3675

Can you check that:

  • edgesForExtendedLayout contains the upper edge
  • automaticallyAdjustsScrollViewInsets is set on your view controller?

Upvotes: 0

Related Questions