【iOS】キーボードの表示に合わせてUITextField上げ下げ

あ、どーもこんばんわ。

キーボードの表示に合わせてUITextField上げ下げです。
やり方忘れていっつもググるんだけど、みんな無駄なことしすぎなんすよねー

なんと!初めての画像つき!
こんなやつです。

キーボード非表示のとき↓
f:id:devdevdev:20140120001640p:plain

キーボード表示したとき↓
f:id:devdevdev:20140120001647p:plain



LINEとかもこんな感じですねー

はい、storyboardはこんな感じ↓
UIToolBarについては別途。。。
TextFieldのdelegateはViewControllerに接続しといてくださいねー
Outletも忘れずにー
f:id:devdevdev:20140120001657p:plain
f:id:devdevdev:20140120001652p:plain



はい、ヘッダーから
HogeViewController.h

@interface HogeViewController : UIViewController<UITextFieldDelegate>

@end



次は実装
HogeViewController.m

@interface HogeViewController ()

@property (weak, nonatomic) IBOutlet UITextField *textField;

@end

@implementation HogeViewController

// viewが表示される時に呼び出されますー
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    // キーボードの表示・非表示はNotificationCenterから通知されますよっと
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

// viewが非表示になる時に呼び出されますー
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    // ちゃんとremoveしてあげましょーねー
    // 今回はviewWillAppearで通知登録なので、viewWillDisappearでやりますよっと
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

// キーボードが表示される時に呼び出されますー
- (void)keyboardWillShow:(NSNotification *)notification {
    // キーボードのサイズ
    CGRect keyboardRect = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];

    // キーボード表示アニメーションのduration
    NSTimeInterval duration = [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];

    // viewのアニメーション
    [UIView animateWithDuration:duration animations:^{
        // ここをframeわざわざ計算してる人おおいですねー
        CGAffineTransform transform = CGAffineTransformMakeTranslation(0, -keyboardRect.size.height);
        self.view.transform = transform;
    } completion:NULL];
}

// キーボードが非表示になる時に呼び出されますー
- (void)keyboardWillHide:(NSNotification *)notification {
    // キーボード表示アニメーションのduration
    NSTimeInterval duration = [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];

    __weak typeof(self) _self = self;
    [UIView animateWithDuration:duration animations:^{
        // tranformで動かしておけば、戻すときはこれだけ!
        _self.view.transform = CGAffineTransformIdentity;
    } completion:NULL];
}

// キーボードで確定がタップされた時に呼び出されますー
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    // キーボードを非表示にするにはこう!
    [textField resignFirstResponder];
    return YES;
}

@end



今回はUITextFieldを画面の一番下に置いてるからこれだけですねー
明日は月曜か・・・