self.view 设置框架在键盘显示时不起作用

self.view set frame not work when keyboard show

我遇到了一个问题 -- 当键盘显示时,我的代码将设置视图控制器的视图框架大小,因此通过约束设置,所有组件都将处于正确的位置。然而,有时它会像左图一样工作,但如果我从某些特定点进入这个视图控制器,它会看起来像右图。

这是我检测到键盘出现时的代码..

- (void)moveTextViewForKeyboard:(NSNotification*)aNotification
                         up:(BOOL)up {

NSDictionary* userInfo = [aNotification userInfo];
NSTimeInterval animationDuration;
UIViewAnimationCurve animationCurve;
CGRect keyboardEndFrame;

[[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&animationCurve];
[[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&animationDuration];
[[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardEndFrame];

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:animationDuration];
[UIView setAnimationCurve:animationCurve];

CGRect keyboardFrame = [self.view convertRect:keyboardEndFrame toView:nil];

CGRect viewFrame = self.view.frame;
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenHeight = screenRect.size.height;

if (up) {
    viewFrame.size.height = screenHeight - (keyboardFrame.size.height) - viewFrame.origin.y;
} else {
    viewFrame.size.height = screenHeight;
}

[self.view setFrame:viewFrame];

[UIView commitAnimations];

}

我已经在这里搜索了几天...仍然没有运气:(有专家可以帮助吗?提前谢谢。

如果您使用的是自动布局,则不应手动设置框架,它可能不会更改界面或可能会弄乱您的 UI。
创建对一个或多个约束的引用,更改它们的 constant 属性 以适应键盘更改,然后要求自动布局使用 setNeedsLayout-layoutIfNeeded

更新布局