Have a reloadData for a UITableView animate when changing

前端 未结 17 2952
感动是毒
感动是毒 2020-11-28 17:25

I have a UITableView that has two modes. When we switch between the modes I have a different number of sections and cells per section. Ideally, it would do some cool anima

17条回答
  •  星月不相逢
    2020-11-28 18:02

    All of these answers assume that you are using a UITableView with only 1 section.

    To accurately handle situations where you have more than 1 section use:

    NSRange range = NSMakeRange(0, myTableView.numberOfSections);
    NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
    [myTableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
    

    (Note: you should make sure that you have more than 0 sections!)

    Another thing to note is that you may run into a NSInternalInconsistencyException if you attempt to simultaneously update your data source with this code. If this is the case, you can use logic similar to this:

    int sectionNumber = 0; //Note that your section may be different
    
    int nextIndex = [currentItems count]; //starting index of newly added items
    
    [myTableView beginUpdates];
    
    for (NSObject *item in itemsToAdd) {
        //Add the item to the data source
        [currentItems addObject:item];
    
        //Add the item to the table view
        NSIndexPath *path = [NSIndexPath indexPathForRow:nextIndex++ inSection:sectionNumber];
        [myTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:path] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
    
    [myTableView endUpdates];
    

提交回复
热议问题