1
votes

Structure:

UIView

BaseView

AutoLayout

  1. Center X
  2. Center Y
  3. Equal Width to SafeView
  4. Equal Height to SafeView

UIView

InnerView (SubView of BaseView)

AutoLayout

  1. Leading
  2. Trailing
  3. Top
  4. Bottom (Create the IBOutLet named "bottomLayoutConstraint")

    - (void)keyBoardWillShow:(NSNotification *)notification {

        NSDictionary *info  = notification.userInfo;
        NSValue      *value = info[UIKeyboardFrameEndUserInfoKey];
        CGRect rawFrame      = [value CGRectValue];
        CGRect keyboardFrame = [self.view convertRect:rawFrame fromView:nil];
        self.bottomLayoutConstraint.constant = CGRectGetHeight(keyboardFrame);
[self.view layoutIfNeeded];

    }

    - (void)keyBoardWillHide:(NSNotification *)notification {

        self.bottomLayoutConstraint.constant = 0.0;

    }

Why there is a gap between Keyboard and the InnerView when keyboard appears?

enter image description here


Edit:

After applying Aleksander Maj's solution the gap reduced to 5px

enter image description here


Edit:

Here is my View hierarchy screenshot

enter image description here

1

1 Answers

4
votes

CGRectGetHeight(keyboardFrame) returns the height of the keyboard counting from the bottom edge of the screen. Meanwhile your bottomLayoutConstraint is pinned to your BaseView's safe area's bottom edge (which is not the same as the bottom edge of the screen). The difference between those two horizontal guides is the height of your gap. You should calculate the constant of the bottomLayoutConstraint in the following way:

if (@available(iOS 11, *)) {
  self.bottomLayoutConstraint.constant = CGRectGetHeight(keyboardFrame) - self.view.safeAreaInsets.bottom
} else {
  self.bottomLayoutConstraint.constant = CGRectGetHeight(keyboardFrame)
}

At least that's what I suspect. I didn't reproduce your view hierarchy.


EDIT:

Could you paste a screenshot of your view hierarchy (with all constraints expanded)? I think your issue with the 5pt gap may have something to do with incorrect constraint constant values.

View hierarchy


EDIT 2:

Safe Area's centerY