我的故事板上有一个用于显示用户登录表单的视图,因此它看起来像这样:主视图 - >滚动视图 - >内容视图 - >两个文本字段和顶部的登录按钮和一个注册按钮位于视图的底部。我使用自动布局,底部按钮有底部空间约束。当我点击文本字段并出现键盘时,我想滚动视图以将大小更改为可见的rect,但内容大小应保持向下滚动到注册按钮,但当滚动视图的大小更改时按钮会向上移动。我怎么能做我想做的事?
键盘出现时我使用此代码:
- (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];
}];
}
答案 0 :(得分:30)
尝试单独保留内容大小,而是调整滚动视图的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;
}
答案 1 :(得分:1)
我找到的最好方法是覆盖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中将违规约束的类类型更改为此类。