2013-11-01 7 views
11

私のストーリーボードでは、ユーザのログインをフォームで表示するために、メインビュー - >スクロールビュー - >コンテンツビュー - > 2つのテキストフィールドとログインボタンがあります。ビューの下部に1つの登録ボタンがあります。私はオートレイアウトを使用し、ボトムボタンにはボトムスペースの制約があります。テキストフィールドをタップしてキーボードが表示されたら、表示矩形にサイズを変更するためにスクロールしたいが、コンテンツサイズは登録ボタンまでスクロールする必要がありますが、スクロールビューのサイズが変わるとボタンが上がります。私は何をしたいのですか?iOS AutoLayout with scrollviewとキーボード

キーボードが表示されたとき、私はこのコードを使用:

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

答えて

29

だけでは、コンテンツのサイズを残してみて、代わりにスクロールビューのcontentInsetプロパティを調整します。次に、制約を混乱させる必要はありません。私が見つけた最良の方法はそうのようなNSLayoutConstraintをオーバーライドすることである

- (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; 
} 
+0

ありがとうございます。できます。 –

+0

偉大な答え;私にとって素晴らしい作品です!ありがとう! –

+1

素敵でシンプルですが、スクロールバーはスクロール/テーブル/コレクションビューの表示部分にサイズ変更されません。 –

1

@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でこのクラスに違反している制約のクラスタイプを変更します。

関連する問題