OGeek|极客世界-中国程序员成长平台

标题: ios - 修改 CellForRowAtIndexPath 中的一个单元格会更改多个单元格 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 12:21
标题: ios - 修改 CellForRowAtIndexPath 中的一个单元格会更改多个单元格

我有一组通过 tableview 显示的名称。您最多可以选择 3 个名称,并且不能重新选择相同的名称。为此,我在 cellForRowAtIndexPath: 中实现了以下代码。当我运行代码时,名称显示得很好,但是有多个红色单元格的名称是我没有选择的。

-(UITableViewCell *)tableViewUITableView *)tableView cellForRowAtIndexPathNSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"TableCell";

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

    // Configure the cell...
    NSString *sectionTitle = [nameSectionTitles objectAtIndex:indexPath.section];
    NSArray *sectionNames = [names objectForKey:sectionTitle];
    NSString *name = [sectionNames objectAtIndex:indexPath.row];
    cell.textLabel.text = name;

    if ([name isEqualToString: self.name1] || [name isEqualToString: self.name2] || [name isEqualToString: self.name3]) {
        [cell setUserInteractionEnabled:NO];
        cell.backgroundColor = [UIColor redColor];
        cell.accessoryType = UITableViewCellAccessoryNone;
    }

    return cell;
}

阅读类似问题here ,他们说这是因为单元格被重用了 - 但如果这是真的,表格 View 如何仍然在正确的位置显示正确的名称?

我试着把代码简化成这样,还是没用,有多个红细胞。

myIP = [NSIndexPath indexPathForRow:0 inSection:0];


-(UITableViewCell *)tableViewUITableView *)tableView cellForRowAtIndexPathNSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"TableCell";

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

    // Configure the cell...
    NSString *sectionTitle = [nameSectionTitles objectAtIndex:indexPath.section];
    NSArray *sectionNames = [names objectForKey:sectionTitle];
    NSString *name = [sectionNames objectAtIndex:indexPath.row];
    cell.textLabel.text = name;

    if (indexPath == myIP) {
        cell.backgroundColor = [UIColor redColor];
    }

    return cell;
}

如果需要,我可以发布屏幕截图。注意:预期名称已正确标记为红色。



Best Answer-推荐答案


由于单元重复使用而发生此问题。当重新使用具有红色背景的单元格时,它仍将处于红色背景中,您不会在代码中的任何位置重新设置它。您需要为 cellForRowAtIndexPath: 方法中使用的 if 条件添加一个 else 案例。

if ([name isEqualToString: self.name1] || [name isEqualToString: self.name2] || [name isEqualToString: self.name3])
{
    [cell setUserInteractionEnabled:NO];
    cell.backgroundColor = [UIColor redColor];
    cell.accessoryType = UITableViewCellAccessoryNone;
}
else
{
    [cell setUserInteractionEnabled:YES];
    cell.backgroundColor = [UIColor clearColor];
    // Other stuffs
}

关于ios - 修改 CellForRowAtIndexPath 中的一个单元格会更改多个单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34423505/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://jike.in/) Powered by Discuz! X3.4