Why does my UITableView “jump” when inserting or removing a row?

后端 未结 10 1175
小蘑菇
小蘑菇 2020-12-05 10:21

(Happy to accept an answer in Swift or Objective-C)

My table view has a few sections, and when a button is pressed, I want to insert a row at the end of section 0.

10条回答
  •  既然无缘
    2020-12-05 10:28

    What everyone is saying about estimated row heights is true. So taking all of that into consideration here's the idea:

    Store the heights of each row in a data structure (I choose a dictionary), then use that value from the dictionary for heightForRowAtIndexPath AND estimatedHeightForRowAtIndexPath methods

    So the question is, how to get the row height if you are using dynamic label sizing. Well simple, just use the willDisplayCell method to find the cell frame

    Here is my total working version, and sorry for the objective c...its just the project I'm working on right now:

    declare a property for your dictionary:

    @property (strong) NSMutableDictionary *dictionaryCellHeights;
    

    init the dictionary:

    self.dictionaryCellHeights = [[NSMutableDictionary alloc]init];
    

    capture height:

    -(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    
      NSNumber *height = [NSNumber numberWithDouble:cell.frame.size.height];
        NSString *rowString = [NSString stringWithFormat:@"%d", indexPath.row];
        [self.dictionaryCellHeights setObject:height forKey:rowString];
    }
    

    use height:

    -(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{
        NSNumber *height = [self getRowHeight:indexPath.row];
        if (height == nil){
            return UITableViewAutomaticDimension;
        }
        return height.doubleValue;
    }
    
    -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
        NSNumber *height = [self getRowHeight:indexPath.row];
        if (height == nil){
            return UITableViewAutomaticDimension;
        }
        return height.doubleValue;
    }
    
    -(NSNumber*)getRowHeight: (int)row{
        NSString *rowString = [NSString stringWithFormat:@"%d", row];
        return [self.dictionaryCellHeights objectForKey:rowString];
    }
    

    Then when inserting the rows:

    [self.tableViewTouchActivities performBatchUpdates:^{
                 [self.tableViewTouchActivities insertRowsAtIndexPaths:toInsertIndexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
            } completion:^(BOOL finished){
                [self.tableViewTouchActivities finishInfiniteScroll];
            }];
    

    *note - I'm using this library for infiniteScrolling https://github.com/pronebird/UIScrollView-InfiniteScroll/blob/master/README.md

提交回复
热议问题