2013-11-01 3 views
11

내 스토리 보드에 하나의보기가있어 사용자 로그인 양식을 표시하므로 기본보기 -> 스크롤보기 -> 콘텐츠보기 -> 두 개의 텍스트 입력란과 상단과 하단에있는 하나의 등록 버튼. 나는 자동 레이아웃을 사용하고 아래쪽 버튼에는 아래쪽 공간 제약이 있습니다. 텍스트 필드를 탭하면 키보드가 나타나서 크기를 표시되는 rect로 변경하려면보기를 스크롤하고 싶지만 내용 크기는 등록 단추까지 스크롤해야하지만 스크롤보기의 크기가 변경되면 단추가 위로 이동해야합니다. 나는 내가 원하는 것을 어떻게 할 수 있을까? 키보드가 나타날 때iOS AutoLayout (스크롤보기 및 키보드 포함)

은이 코드를 사용

- (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 속성을 조정합니다. 그렇다면 제약 조건을 망칠 필요가 없습니다.

- (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

내가 찾은 가장 좋은 방법은과 같이 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이 클래스에 위반 제약의 클래스 유형을 변경합니다.