Autolayout Constraint - Keyboard

后端 未结 4 1173
迷失自我
迷失自我 2020-12-22 19:05

Im stuck trying to animate a table view smoothly which has an autolayout contraint. I have a reference to the constraint \"keyboardHeight\" in my .h and have linked this up

4条回答
  •  我在风中等你
    2020-12-22 19:25

    Try the next code. In this case table view lays out at the bottom edge of the screen.

    - (void)keyboardWillShow:(NSNotification *)notification { // UIKeyboardWillShowNotification
    
        NSDictionary *info = [notification userInfo];
        NSValue *keyboardFrameValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
        NSTimeInterval animationDuration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
        CGRect keyboardFrame = [keyboardFrameValue CGRectValue];
    
        BOOL isPortrait = UIDeviceOrientationIsPortrait([UIApplication sharedApplication].statusBarOrientation);
        CGFloat keyboardHeight = isPortrait ? keyboardFrame.size.height : keyboardFrame.size.width;
    
        // constrBottom is a constraint defining distance between bottom edge of tableView and bottom edge of its superview
        constrBottom.constant = keyboardHeight; 
        // or constrBottom.constant = -keyboardHeight - in case if you create constrBottom in code (NSLayoutConstraint constraintWithItem:...:toItem:...) and set views in inverted order
    
        [UIView animateWithDuration:animationDuration animations:^{
            [tableView layoutIfNeeded];
        }];
    }
    
    
    - (void)keyboardWillHide:(NSNotification *)notification { // UIKeyboardWillHideNotification
    
        NSDictionary *info = [notification userInfo];
        NSTimeInterval animationDuration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
        constrBottom.constant = 0;
        [UIView animateWithDuration:animationDuration animations:^{
            [tableView layoutIfNeeded];
        }];
    }
    

提交回复
热议问题