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

时间:2016-04-08 03:38:50

标签: ios keyboard resize frame

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

enter image description here

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

- (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];

}

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

1 个答案:

答案 0 :(得分:2)

如果您正在使用自动布局,则不应手动设置框架可能不会更改界面或可能会弄乱您的UI。
创建对一个或多个约束的引用,更改其{{1 }}属性以适应键盘更改,然后要求autolayout使用constantsetNeedsLayout

更新布局