iOSアプリ開発のメモ置き場

ささたつがiOSアプリ開発で知ったObjective-Cのtipsなどを書いていく所存

キーボードを表示したときに、UITextField が隠れないようにする方法

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self registerForKeyboardNotifications];
}

// キーボードの表示/非表示の通知を受け取る
- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeShown:)
                                                 name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyboardWillBeShown:(NSNotification*)aNotification
{
    NSDictionary *dictionary = [aNotification userInfo];
    
    // アニメーション終了時のキーボードの CGRect
    CGRect keyboardRect = [[dictionary objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    NSTimeInterval duration = [[dictionary objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    UIViewAnimationCurve animationCurve = [[dictionary objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
    
    // 実際にアニメーションさせる
    [UIView animateWithDuration:duration
                         delay:0.0f
                       options:animationCurve
                     animations:^{
                         CGPoint scrollPoint = CGPointMake(0, keyboardRect.size.height);
                         [self.scrollView setContentOffset:scrollPoint animated:YES]; // contentOffset を指定
                     }
                     completion:nil];
}

- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    [self.scrollView setContentOffset:CGPointZero animated:YES];
}