LoginSignup
4
4

More than 5 years have passed since last update.

キーボードがどこに表示されているかを知る方法

Last updated at Posted at 2015-08-18

キーボードの表示に合わせて View の状態を変えたい

キーボードの表示に合わせて View の状態を変えたい事ってよくありますよね。
特に iPhone なんかだと画面も小さく、UITextField が画面下方にあることとかもよくあります。
こんな時、キーボードが表示されたタイミングで画面をスクロールさせて、キーボードの表示領域を避けるなどの調整をしたいわけです。

けっこうググれば直ぐに出てくる情報ですが、自分が忘れがちなのでメモ。

キーボード表示イベントを登録する

以下のようにしてキーボード表示イベントを獲得するよう宣言します。

NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self
           selector:@selector(keyboardWillChangeSize:)
               name:UIKeyboardWillChangeFrameNotification
             object:nil];

いちおう念のため、 dealloc 時にはイベント登録解除しておきます。

- (void)dealloc {
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center removeObserver:self
                forKeyPath:UIKeyboardWillChangeFrameNotification];
}

イベントを受けるメソッドを実装する

上記の例に挙げたように、keyboardWillChangeSize:メソッドを実装します。

- (void)keyboardWillChangeSize:(NSNotification *)notif {
    //キーボードの表示領域を得る
    NSValue *value = notif.userInfo[UIKeyboardFrameEndUserInfoKey];
    CGRect keyRect = value.CGRectValue;

    //
    //キーボード表示領域に合わせて View を動かすなど...
    //
}
4
4
1

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