UITableView repeating cells when scrolled

前端 未结 2 946
名媛妹妹
名媛妹妹 2021-01-22 14:06

When i scroll down my UITableView, it starts showing me the same cells that i\'ve already seen, and scrolling around a bit continues to put cells in the wrong place.

Her

2条回答
  •  半阙折子戏
    2021-01-22 14:41

    It looks as if you are only setting the cell content when the you're getting a nil back from dequeueReusableCellWithIdentifier. You need to set the cell contents every time, not just when you need to create a new cell.

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
    static NSString *CellIdentifier = @"Cell";
    
        AHCell *cell = (AHCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil)
        {
            // create a new cell if there isn't one available to recycle
            // cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
            cell = [AHCell blankCell];
    
        }
    
        // set the contents of the cell (whether it's a new one OR a recycled one)
        NSString *vaultsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Vaults"];
    
        NSString *dictionaryPath = [NSString stringWithFormat:@"%@/%@",
                                    vaultsPath,
                                    [self.allVaults objectAtIndex:indexPath.row]];
    
        NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:dictionaryPath];
    
        cell.backgroundView = [AHCellCreation backgroundView];
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
        cell.selectedBackgroundView = [AHCellCreation selectedBackgroundView];
        // cell = [AHCellCreation createCellWithDictionary:dictionary Cell:cell];
        [cell populateAHCellWithDictionary: dictionary];
        return cell;
        }
    

    Update updated code to address second issue. Rework AHCell so that the class method, e.g. blankCell returns a new cell with the subviews set up and the instance method, e.g. populateAHCellWithDictionary: sets the content.

提交回复
热议问题