AutoLayout constraint constant change causes button to disappear

Discussion in 'iOS Programming' started by moonman239, Jul 26, 2016.

  1. moonman239, Jul 26, 2016
    Last edited: Jul 26, 2016

    moonman239 macrumors 68000

    Joined:
    Mar 27, 2009
    #1
    I have a button with a constraint that relates the button's bottom to the bottom layout guide. Upon tapping on a UITextField, thus bringing up the default software keyboard, the keyboard hides the button. The aforementioned constraint's constant is supposed to be set such that the button shifts far enough upward that the button is not hidden, but the latter is not happening. Instead, the button appears to be going offscreen.

    Edit: The button in question also has a height constraint that keeps the height constant, but that constraint is orange. However, the width constraint is red.

    Here is the code that causes the change:

    Code:
    -(void)keyboardDidShow:(NSNotification *)notification
    {
        CGRect keyboardFrameInWindow = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
        CGRect keyboardFrame = [self.viewconvertRect:keyboardFrameInWindow fromView:self.view.window];
    
        NSInteger constant = CGRectGetMaxY(self.view.bounds) - CGRectGetMinY(keyboardFrame);
    
        buttonConstraint.constant = constant;
    }
    
     
  2. jgaz macrumors member

    jgaz

    Joined:
    Dec 30, 2007
    Location:
    Colorado
    #2
    I am not sure about your geometry but the main problem might be you aren't notifying the system that you have changed the constraints. After you change the constraint you should call:

    Code:
    [self.view layoutIfNeeded];
    

    If it still seems to be moving it off screen you might use this snippet instead to get the height of the keyboard, I have used this before with good results:

    Code:
    - (void)keyboardDidShow:(NSNotification *)sender {
        CGRect frame = [sender.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
        CGRect newFrame = [self.view convertRect:frame fromView:[[UIApplication sharedApplication] delegate].window];
        self.bottomConstraint.constant = newFrame.origin.y - CGRectGetHeight(self.view.frame);
        [self.view layoutIfNeeded];
    }
    
    --- Post Merged, Jul 27, 2016 ---
    on a side note it looks nice if you throw the [self.view layoutIfNeeded] call in an animation block so the button animates up with the keyboard.
     

Share This Page