iOS UITableView Cell loads incorrectly after scroll?

时光怂恿深爱的人放手 提交于 2019-12-25 01:25:34

问题


I'm having 2 UITableView in a view and I added the UITableViewCellAccessoryDisclosureIndicator only at the 2nd table row 5 and row 7.

But after scrolling the 2nd table down (which row 1 disappears) and then scroll back to top (which row 1 appears), row 1 now has the UITableViewCellAccessoryDisclosureIndicator?! Did row 1 somehow become row 5 or row 7??? Below is my code for cellForRowAtIndexPath:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{    
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    cell.textLabel.textColor = [UIColor blueColor];
    cell.detailTextLabel.textColor = [UIColor blackColor];
    if (tableView == table1)
    {
        cell.textLabel.text = [title1 objectAtIndex:indexPath.row];
        cell.detailTextLabel.text = [list1 objectAtIndex:indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    else if (tableView == table2)
    {
        cell.textLabel.text = [title2 objectAtIndex:indexPath.row];
        cell.detailTextLabel.text = [list2 objectAtIndex:indexPath.row];
        if (indexPath.row == 5 || indexPath.row == 7)
        {
            cell.selectionStyle = UITableViewCellSelectionStyleBlue;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        else
        {
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
    }
    return cell;
}

Thanks a lot!


回答1:


UITableViewCells are reused to optimize performance. This happens in [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; You need to explicitly set any properties you would like on the cell at each call of tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath .

Something like this should resolve the issue:

if (indexPath.row == 5 || indexPath.row == 7)
        {
            cell.selectionStyle = UITableViewCellSelectionStyleBlue;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        else
        {
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.accessoryType = UITableViewCellAccessoryNone;
        }


来源:https://stackoverflow.com/questions/7614845/ios-uitableview-cell-loads-incorrectly-after-scroll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!