移动位于键盘下方的表单内容

时间:2013-02-14 01:22:24

标签: ios uitableview uikeyboard

我正在使用UITableView,其中每个单元格都包含UITextField,并且使用Apple官方示例,我希望执行目标,如果已经隐藏了键盘上方的活动字段。但是,虽然UITableView是滚动的,但表单不会移动。这是我的相关代码,请帮我指出似乎缺失/错误的内容:

@interface ViewController (){
    UITextField *activeField;
}

- (void)viewDidLoad
{
//....
    objTableView.scrollEnabled=YES;

//....
}

#pragma mark - Keyboard notifications

// Call this method somewhere in your view controller setup code.
- (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);

    objTableView.contentInset = contentInsets;

    objTableView.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, activeField.frame.origin) ) {

        CGPoint scrollPoint = CGPointMake(0.0, activeField.frame.origin.y-kbSize.height);

        [objTableView setContentOffset:scrollPoint animated:YES];

    }

}



// Called when the UIKeyboardWillHideNotification is sent

- (void)keyboardWillBeHidden:(NSNotification*)aNotification

{

    UIEdgeInsets contentInsets = UIEdgeInsetsZero;

    objTableView.contentInset = contentInsets;

    objTableView.scrollIndicatorInsets = contentInsets;

}
#pragma mark - UITextFieldDelegate protocol method

- (void)textFieldDidBeginEditing:(UITextField *)textField

{

    activeField = textField;

}
- (void)textFieldDidEndEditing:(UITextField *)textField

{

    activeField = nil;

}

1 个答案:

答案 0 :(得分:0)

试试这段代码:

if (!CGRectContainsPoint(aRect, activeField.frame.origin) ) {
    CGRect rc = [activeField bounds];
    rc = [activeField convertRect:rc toView:objTableView];
    [objTableView scrollRectToVisible:rc animated:YES];
}