UITableView with dynamic cell heights jumping when scrolling up after reloading cell

后端 未结 5 1418
孤街浪徒
孤街浪徒 2021-02-05 13:21

I have a table view with the potential for each cell to have its own height, thus isn\'t suitable to use rowHeight. Instead, right now I\'m using let indexSet

5条回答
  •  借酒劲吻你
    2021-02-05 14:05

    I had this issue too and used a solution from SO which I am unable to find right now. If I do, I will add the link. Here's the solution:

    The issue is with table view not having the right estimate for height of rows. To fix it, cache the height initially in willDisplayCell and next time use that height.

    Code

    In viewDidLoad:

    heightAtIndexPath = [NSMutableDictionary new];
    
    
    - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
        NSNumber *height = @(cell.frame.size.height);
        [heightAtIndexPath setObject:height forKey:indexPath];
    }
    
    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
        return UITableViewAutomaticDimension;
    }
    
    - (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{
        if([heightAtIndexPath objectForKey:indexPath]) {
            return [[heightAtIndexPath objectForKey:indexPath] floatValue];
        } else {
            return UITableViewAutomaticDimension;
        }
    }
    

提交回复
热议问题