キーボードの動きにあわせてUITextFieldを移動する

現時点(2012/11/14)でのiOSFacebookアプリで、

あるポストにコメントしようとするときには以下のような画面の動きになる。

 

f:id:ushisantoasobu:20121114021819p:plain

 

f:id:ushisantoasobu:20121114021830p:plain

 

ポイントとしては、

・コメントを入力するテキストインプットが画面の一番下にあって

・それをタップしたときにキーボードが下からアニメーションつきでせり上がってきて、

 その動きにあわせてテキストインプットも下から平行移動する

というところだ。

 

これらの一連の動作の実装の仕方を今回は記載する。

 

参考にしたのはこちらのサイト、

http://runlooprun.wordpress.com/2011/03/27/linktextviewwithkeybaord/

大変わかりやすかくこちらだけでも十分なのですが、自分の頭の整理のためにこちらでもまとめさせていただきます。。。

 

 

 

以下3つの手順をたどって実装していきます。

 

1)キーボードが「表示しはじめる」「隠れはじめる」通知をNSNotificationで受け取るよう設定する

 

    //キーボードが表示されようとするるとき

    [[NSNotificationCenterdefaultCenter] addObserver:self

                                             selector:@selector(respondToKeyboardWillShow:)

                                                 name:UIKeyboardWillShowNotification

                                               object:nil];

    

    //キーボードがかくれようとするとき

    [[NSNotificationCenterdefaultCenter] addObserver:self

                                             selector:@selector(respondToKeyboardWillHide:)

                                                 name:UIKeyboardWillHideNotification

                                               object:nil];

 

 

2)キーボードに関する情報を取得する

 

1)のそれぞれのセレクターで、必要な情報をnotificationのuserInfoから取得する。

以下の3つの情報があればよい。

 

- (void)respondToKeyboardWillShow:(NSNotification *)ns {

    

    NSDictionary *dic = [ns userInfo];

    

    //アニメーション終了時のキーボードのCGRect

    CGRect keyboardRect         = [[dic objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];

    

    //アニメーションにかかる時間

    NSTimeInterval duration     = [[dic objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];

    

    //アニメーションのタイプ

    UIViewAnimationCurve curve  = [[dic objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];

 

    //

    //

    //

}

 

 

3)2)で取得した情報をもとに、テキストインプットをキーボードにあわせてアニメーションさせる

  (_viewTestはテキストインプットをaddしているUIView)

 

- (void)respondToKeyboardWillShow:(NSNotification *)ns {

    

    //

    //

    //

 

    void (^animations)(void);

    animations = ^(void) {

        _viewTest.frame = CGRectMake(_viewTest.frame.origin.x,

                                     _viewTest.frame.origin.y - keyboardRect.size.height,

                                     _viewTest.frame.size.width,

                                     _viewTest.frame.size.height);

    };

    [UIViewanimateWithDuration:duration

                          delay:0.0f

                        options:curve

                     animations:animations

                     completion:nil];

    

}

 

キーボードを隠すときも上記を同様の手順で実装できる。