1

メールフィールドをクリックしてキーボードがポップアップすると、ビューが上に移動するようにしようとしています。しかし、現在、このコードでは、どのテキストフィールドをクリックしてもビューが上に移動します。また、キーボードを閉じることができません。アクティブなフィールドにのみスクロールするようにこのコードを設定する方法がわかりませんか?

コード:

- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
}

// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
    scrollView.contentInset = contentInsets;
    scrollView.scrollIndicatorInsets = contentInsets;

    // If active text field is hidden by keyboard, scroll it so it's visible
    // Your application might not need or want this behavior.
    CGRect aRect = self.view.frame;
    aRect.size.height -= kbSize.height;
    if (!CGRectContainsPoint(aRect, self.emailField.frame.origin) ) {
        CGPoint scrollPoint = CGPointMake(0.0, self.emailField.frame.origin.y-kbSize.height);
        [scrollView setContentOffset:scrollPoint animated:YES];
    }
}

// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    scrollView.contentInset = contentInsets;
    scrollView.scrollIndicatorInsets = contentInsets;
}

このようなビューがあります(スクロールビューにあります)

見る

4

2 に答える 2

3

これには、キーボードの表示/非表示の通知を無視して、UITextFieldDelegateプロトコルのみを使用できます。

– (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if([textField isEqual:self.emailTextField]){
        // scroll up
    }
    return true;
}

– (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    if([textField isEqual:self.emailTextField]){
        // scroll back to start
    }
    return true;
}
于 2013-05-17T14:28:12.060 に答える