Auto Layout을 사용하여 키보드에 맞게 뷰를 크기 조정하는 방법

iOS6에서 사용할 수 있는 Auto Layout을 이용하여 키보드가 표시/숨겨지면 UITextView를 리사이즈해 봅니다.

Constraint 설정



UITextView를 붙여넣습니다.
UITextView

UITextView의 Constraints의 Bottom Space to: Superview를 View Controller의 outlet으로 설정합니다.

Vertical Space
Outlet

CTViewController.h
@interface CTViewController : UIViewController
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomConstraint;
@end

키보드 개폐를 모니터링하고 재 레이아웃



키보드의 개폐를 감시해, constraint 에 값을 설정해 재레이아웃을 실시합니다. bottomConstraint는 키보드 높이의 마이너스 값을 설정합니다.

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

- (void)keyboardWillShow:(NSNotification *)notification {
    NSDictionary *info = [notification userInfo];
    CGRect keyboardFrame = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSTimeInterval duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];

    self.bottomConstraint.constant = keyboardFrame.size.height;

    [UIView animateWithDuration:duration animations:^{
        [self.view layoutIfNeeded];
    }];
}

- (void)keyboardWillHide:(NSNotification *)notification {
    NSDictionary *info = [notification userInfo];
    NSTimeInterval duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];

    self.bottomConstraint.constant = 0;

    [UIView animateWithDuration:duration animations:^{
        [self.view layoutIfNeeded];
    }];
}

이제 UITextView를 터치하면 자동으로 UITextView가 축소되어 키보드의 높이에 맞게 되었습니다.

좋은 웹페이지 즐겨찾기