0

I'm a big fan of autolayout, but have always implemented it in Storyboard.

I have a UIView that I want the bottom space constraint to be where the keyboard ends.

I have defined all my constraints, can someone show me how to implement this constraint in code for just the bottom space? And also how to get the value of the keyboard height depending on the specific iDevice and match that to the constraint.

Thanks

nickjf89
  • 458
  • 1
  • 7
  • 18

1 Answers1

2

Take an outlet of the bottom constraint of the view like this

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *constraintContainerBottom;

and use this

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self setupKeyboard:YES];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self setupKeyboard:NO];
}

- (void)setupKeyboard:(BOOL)appearing
{
    if (appearing) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    }else{
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    }
}

- (void)keyboardWillShow:(NSNotification*)notification
{
    CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    double duration = [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    int curve = [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue];
    [UIView beginAnimations:@"keyboardShown" context:nil];
    [UIView setAnimationDuration:duration];
    [UIView setAnimationCurve:curve];

    self.constraintContainerBottom.constant = keyboardSize.height;
    [self.view layoutIfNeeded];

    [UIView setAnimationDelegate:self];
    [UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification*)notification
{
    double duration = [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    int curve = [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue];
    [UIView beginAnimations:@"keyboardHidden" context:nil];
    [UIView setAnimationDuration:duration];
    [UIView setAnimationCurve:curve];

    self.constraintContainerBottom.constant = 0;
    [self.view layoutIfNeeded];

    [UIView setAnimationDelegate:self];
    [UIView commitAnimations];
}
Mahesh Agrawal
  • 3,348
  • 20
  • 34