ios - 使用键盘和中心自动布局管理 View

标签 ios objective-c keyboard autolayout

我有以下 View 层次结构。 View->container->containerView 中的 2 个 UITextfields 和 1 个 button。容器位于屏幕中央。我想要做的是当键盘出现并且 UITextfield 位于键盘后面时将容器向上移动,并在键盘消失时移回中心。这是相同的屏幕截图。

enter image description here

我需要更改哪些约束或者需要在代码中添加约束?

最佳答案

在键盘显示时获取容器的框架并更新新的框架大小。 “setTranslatesAutoresizingMaskIntoConstraints”是更新 View 框架时的正确解决方案。它对我有用

enter image description here

 @implementation ViewController
{
CGRect defaultFrame;
}

- (void)viewDidLoad {
[super viewDidLoad];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
#pragma mark Notifications

- (void)keyboardWillShow:(NSNotification *)notification {
CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
defaultFrame = self.ContentView.frame;

[self.ContentView setTranslatesAutoresizingMaskIntoConstraints:YES];
[self.ContentView layoutIfNeeded];

CGRect contentInsets = CGRectMake(defaultFrame.origin.x, (keyboardSize.height), defaultFrame.size.width, defaultFrame.size.height);
[UIView animateWithDuration:0.5f
                 animations:^{
                     self.ContentView.frame = contentInsets;

                 }
                 completion:^(BOOL finished){

                 }
 ];

self.ContentView.frame = contentInsets;

}

- (void)keyboardWillHide:(NSNotification *)notification {
[self.ContentView setTranslatesAutoresizingMaskIntoConstraints:NO];
[UIView animateWithDuration:0.5f
                 animations:^{
                     self.ContentView.frame = defaultFrame;
                 }
                 completion:^(BOOL finished){

                 }
 ];

}

关于ios - 使用键盘和中心自动布局管理 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36740564/

相关文章:

IOS 8 无法从 UITextField 中关闭键盘

iphone - 通过数组进行页面控制

iphone - 启用表格 View 编辑时设置 UITableviewcell 框架

ios - UITableViewCell 通过内容拥抱自动调整大小

html - 如果在 UIWebView 中加载网页,iOS 6 "HTML Input file tag"不起作用

java - 在 Swing 中使用印度语输入法输入文本时不显示英文字符

c - Number Pad [Enter] 不在 C 中?

ios - 如果未安装应用程序,请打开网页