0

我正在使用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;

}
4

1 回答 1

0

试试这个代码:

if (!CGRectContainsPoint(aRect, activeField.frame.origin) ) {
    CGRect rc = [activeField bounds];
    rc = [activeField convertRect:rc toView:objTableView];
    [objTableView scrollRectToVisible:rc animated:YES];
}
于 2013-02-14T03:51:51.917 回答