具有滚动视图和键盘的iOS AutoLayout

我有一个视图在我的故事板上显示用户login窗体,所以它看起来像这样:主视图 – >滚动视图 – >内容视图 – >两个文本字段和顶部loginbutton和一个注册button在底部风景。 我使用自动布局,底部button有底部空间的限制。 当我点击文本字段和键盘出现我想滚动视图更改大小可见矩形,但内容大小应保持向下滚动到注册button,但滚动视图的大小更改时button向上移动。 我怎么能做我想要的?

出现键盘时使用此代码:

- (void)keyboardWillShow:(NSNotification *)aNotification { NSDictionary *info = [aNotification userInfo]; NSValue *kbFrame = [info objectForKey:UIKeyboardFrameEndUserInfoKey]; NSTimeInterval animationDuration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]; CGRect keyboardFrame = [kbFrame CGRectValue]; CGSize s = self.scrollView.contentSize; CGFloat height = keyboardFrame.size.height; self.scrollViewBottomLayoutConstraint.constant = height; [UIView animateWithDuration:animationDuration animations:^{ [self.view layoutIfNeeded]; [self.scrollView setContentSize:s]; }]; } 

尝试单独留下内容大小,而是调整滚动视图的contentInset属性。 那么你就不必拘泥于限制。

 - (void)keyboardUp:(NSNotification *)notification { NSDictionary *info = [notification userInfo]; CGRect keyboardRect = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue]; keyboardRect = [self.view convertRect:keyboardRect fromView:nil]; UIEdgeInsets contentInset = self.scrollView.contentInset; contentInset.bottom = keyboardRect.size.height; self.scrollView.contentInset = contentInset; } 

我发现的最好的方法是覆盖NSLayoutConstraint像这样:

 @implementation NHKeyboardLayoutConstraint - (void) dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; } - (void) awakeFromNib { [super awakeFromNib]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil]; } - (void)keyboardWillChangeFrame:(NSNotification *)notification { CGRect endKBRect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue]; CGFloat animationDuration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue]; CGRect frame = [UIApplication sharedApplication].keyWindow.bounds; self.constant = frame.size.height - endKBRect.origin.y; [UIView animateWithDuration:animationDuration animations:^{ [[UIApplication sharedApplication].keyWindow layoutIfNeeded]; }]; } @end 

然后在你的xib中将违规约束的类types改为这个类。