xCode 4.2将一个UISwitch分配给一个部分的一行会产生奇怪的行为..IOS



我正在制作一个设置页面,希望第一部分的第一行有一个UISwitch。我使用以下代码实现了这一点:

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
    }
    if (indexPath.section == 0){
        [[cell textLabel] setText:[table1labels objectAtIndex:indexPath.row]];
        if (indexPath.row == 0 && indexPath.section == 0){
            UISwitch *switchview = [[UISwitch alloc] initWithFrame:CGRectZero];
            cell.accessoryView = switchview;
        }else{
            [[cell detailTextLabel] setText:@"test"];
        }
    }else{
        [[cell textLabel] setText:[table2labels objectAtIndex:indexPath.row]];
        [[cell detailTextLabel] setText:@"test"];
    }
    return cell;
}

当页面加载时,第一部分的第一行有一个UISwitch,所有其他行都说"test"。然而,当我在页面上滚动时,会随机出现更多的UISwitch。它们不会替换文本"test",只是将其向左推。这并不是发生在他们每个人身上。当一个单元格离开视图并返回视图时,只是随机的。有人能告诉我怎么解决这个问题吗?

我只在5.1模拟器上测试过。还没有在实际的设备上。这可能只是模拟器的问题吗?

您不断重复使用同一个单元格,这是问题的重要部分。

现在假设一个最初用于UISwitch的单元格被重新用于一个与您想要显示它的索引不相等的索引。在这种情况下,您必须手动隐藏或替换UISwitch。

作为一种替代方案,我强烈建议您对实际看起来不相似的细胞使用不同的细胞标识符。

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier;
    if (indexPath.row == 0 && indexPath.section == 0)
    {
        cellIdentifier = @"CellWithSwitch";
    }
    else
    {
        cellIdentifier = @"PlainCell";
    }
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier];
    }
    if (indexPath.section == 0)
    {
        [[cell textLabel] setText:[table1labels objectAtIndex:indexPath.row]];
        if (indexPath.row == 0 && indexPath.section == 0)
        {
            UISwitch *switchview = [[UISwitch alloc] initWithFrame:CGRectZero];
            cell.accessoryView = switchview;
        }
        else
        {
            [[cell detailTextLabel] setText:@"test"];
        }
    }else{
        [[cell textLabel] setText:[table2labels objectAtIndex:indexPath.row]];
        [[cell detailTextLabel] setText:@"test"];
    }
    return cell;
}

相关内容

最新更新