我正在设置页面,并希望第一部分的第一行有一个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;
}

关于ios - xCode 4.2将UISwitch分配给一个部分的一行会产生奇怪的行为……IOS,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9895243/

10-12 00:22
查看更多