Keep uitableview static when inserting rows at the top

后端 未结 18 2091
名媛妹妹
名媛妹妹 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:18

    -(void) updateTableWithNewRowCount : (int) rowCount
    {    
        //Save the tableview content offset 
        CGPoint tableViewOffset = [self.tableView contentOffset];                                                                                                            
    
        //Turn of animations for the update block 
        //to get the effect of adding rows on top of TableView
        [UIView setAnimationsEnabled:NO];
    
        [self.tableView beginUpdates];                    
    
        NSMutableArray *rowsInsertIndexPath = [[NSMutableArray alloc] init];        
    
        int heightForNewRows = 0;
    
        for (NSInteger i = 0; i < rowCount; i++) {
    
            NSIndexPath *tempIndexPath = [NSIndexPath indexPathForRow:i inSection:SECTION_TO_INSERT];
            [rowsInsertIndexPath addObject:tempIndexPath];
    
            heightForNewRows = heightForNewRows + [self heightForCellAtIndexPath:tempIndexPath];                        
        }
    
        [self.tableView insertRowsAtIndexPaths:rowsInsertIndexPath withRowAnimation:UITableViewRowAnimationNone];                                                                            
    
        tableViewOffset.y += heightForNewRows;                                                                                 
    
        [self.tableView endUpdates]; 
    
        [UIView setAnimationsEnabled:YES];
    
        [self.tableView setContentOffset:tableViewOffset animated:NO];           
    }
    
    
    -(int) heightForCellAtIndexPath: (NSIndexPath *) indexPath
    {
    
        UITableViewCell *cell =  [self.tableView cellForRowAtIndexPath:indexPath];
    
        int cellHeight   =  cell.frame.size.height;
    
        return cellHeight;
    }
    

    Simply pass in the row count of the new rows to insert at the top.

提交回复
热议问题