LoginSignup
88
83

More than 5 years have passed since last update.

Auto Layoutを利用してキーボードに合わせてビューをリサイズする方法

Last updated at Posted at 2013-02-13

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が縮小されてキーボードの高さにフィットするようになりました。

88
83
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
88
83