当键盘显示 AutoLayout 时 UIView 没有向上移动

UIView is not moving up when keyboard shown AutoLayout

我的 UIView 在键盘显示时没有向上移动,在键盘隐藏时也没有消失。

此编码在 ViewDidLoad

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil];

此编码用于其余部分。

- (void)keyboardDidShow:(NSNotification *)note
{
    [self animateTextField:TRUE];
}

- (void)keyboardDidHide:(NSNotification *)note
{
    [self animateTextField:FALSE];
}

-(void)animateTextField :(BOOL)up
{
    const int movementDistance = -130; // tweak as needed
    const float movementDuration = 1.0; // tweak as needed

    int movement = (up ? movementDistance : - movementDistance);

    [UIView beginAnimations: @"animateTextField" context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    _buttonsView.frame = CGRectOffset(_buttonsView.frame, 0, movement);
    [UIView commitAnimations];
}

使用自动布局,您可以为约束常量设置动画,但不更改 CGRect 框架。那是老办法。

请看这个link,我回答了一个类似的问题,他们在为 UIView 的移动设置动画时遇到了问题

Animate UIView with layoutConstraints

这应该有所帮助,但如果您需要任何说明,请随时告诉我。

我认为这适合您的实施:

-(void)animateTextField :(BOOL)up
{
    const int movementDistance = -130; // tweak as needed
    const float movementDuration = 1.0; // tweak as needed

    int movement = (moveUp ? movementDistance : - movementDistance);

    [UIView beginAnimations: @"animateTextField" context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    _buttonsView.frame = CGRectOffset(_buttonsView.frame, 0, movement);
    [UIView commitAnimations];

    [_buttonsView setNeedsLayout];
}

编辑

我试过你的代码并调用 setNeedsLayout 完成了工作..

使用下面的代码,您不需要从任何地方调用它

#pragma mark - move view up when keyboard is displayed


- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self animateTextField: textField up: YES];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [self animateTextField: textField up: NO];
}

- (void) animateTextField: (UITextField*) textField up: (BOOL) up
{
    const int movementDistance = 80; // tweak as needed
    const float movementDuration = 0.3f; // tweak as needed

    int movement = (up ? -movementDistance : movementDistance);

    [UIView beginAnimations: @"anim" context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    contentView.frame = CGRectOffset( contentView.frame, 0, movement);
    [UIView commitAnimations];
}