Keep uitableview static when inserting rows at the top

后端 未结 18 2062
名媛妹妹
名媛妹妹 2020-11-29 16:12

I have a tableView that I\'m inserting rows into at the top.

Whilst I\'m doing this I want the current view to stay completely still, so the rows only appear if you

18条回答
  •  既然无缘
    2020-11-29 16:32

    I did some testing with a core data sample project and got it to sit still while new cells were added above the top visible cell. This code would need adjustment for tables with empty space on the screen, but once the screen is filled, it works fine.

    static CGPoint  delayOffset = {0.0};
    
    - (void)controllerWillChangeContent:(NSFetchedResultsController*)controller {
        if ( animateChanges )
            [self.tableView beginUpdates];
        delayOffset = self.tableView.contentOffset; // get the current scroll setting
    }
    

    Added this at cell insertion points. You may make counterpart subtraction for cell deletion.

        case NSFetchedResultsChangeInsert:
    
            delayOffset.y += self.tableView.rowHeight;  // add for each new row
            if ( animateChanges )   
                [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationNone];
            break;
    

    and finally

    - (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
        if ( animateChanges )   
        {
            [self.tableView setContentOffset:delayOffset animated:YES];
            [self.tableView endUpdates];
        }
        else
        {
            [self.tableView reloadData];
            [self.tableView setContentOffset:delayOffset animated:NO];
        }
    }
    

    With animateChanges = NO, I could not see anything move when cells were added.

    In testing with animateChanges = YES, the "judder" was there. It seems the animation of cell insertion did not have the same speed as the animated table scrolling. While the result at the end could end with visible cells exactly where they started, the whole table appears to move 2 or 3 pixels, then move back.

    If the animation speeds could be make to equal, it may appear to stay put.

    However, when I pressed the button to add rows before the previous animation finished, it would abruptly stop the animation and start the next, making an abrupt change of position.

提交回复
热议问题