简体   繁体   中英

UITableView does not scroll cell to visible after UITextField becomes first responder

I have a UITableView loaded with custom cells. Those cells have two possible states: A read-only state, and an edition state. I change between them by tapping the corresponding row in the table view:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomClass *aCustomClass = [self.model objectAtIndex:indexPath.row];
    [aCustomClass setEdition:YES];

    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}

The problem is that I need to set the cell's UITextField as first responder after tapping the row. What I've done is add the following code:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell"];

    if (!cell)
        cell = ... // Create cell

    ...

    [cell.textField becomeFirstResponder];
}

All works well, but when the UITextField becomes first responder I want the table view to scroll the whole cell to visible. For that, I implemented a keyboard notification event like this:

- (void)keyboardWillBeShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGRect kbRawRect = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGRect ownFrame = [self.tableView.window convertRect:self.tableView.frame fromView:self.tableView.superview];

    // Calculate the area that is covered by the keyboard
    CGRect coveredFrame = CGRectIntersection(ownFrame, kbRawRect);

    coveredFrame = [self.tableView.window convertRect:coveredFrame toView:self.tableView.superview];

    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, coveredFrame.size.height, 0.0);
    self.tableView.contentInset = contentInsets;
    self.tableView.scrollIndicatorInsets = contentInsets;

    [self.tableView scrollToRowAtIndexPath:self.openCellIndexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

The problem is, the table view doesn't scroll the cell to the top position, as the last line indicates.

If I remove the automatic becomeFirstResponder call and tap the UITextField manually, all works OK.

Do you have any idea why this is happening and how could I resolve this issue?

Thanks,

UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, coveredFrame.size.height, 0.0);

应该这样改变:

UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, -coveredFrame.size.height, 0.0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM