我有以下 View 层次结构。 View->container->containerView 中的 2 个 UITextfields
和 1 个 button
。容器位于屏幕中央。我想要做的是当键盘出现并且 UITextfield 位于键盘后面时将容器向上移动,并在键盘消失时移回中心。这是相同的屏幕截图。
我需要更改哪些约束或者需要在代码中添加约束?
最佳答案
在键盘显示时获取容器的框架并更新新的框架大小。 “setTranslatesAutoresizingMaskIntoConstraints”是更新 View 框架时的正确解决方案。它对我有用
@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/