UITableView with UISwitch



我使用storyboard和Auto Layout。我将UISwitch添加到标签为5的单元格中。当我选择第一个UISwitch并向下滚动,我看到另一个UISwitch也被打开,如果我向上滚动,我的第一个UISwitch被关闭。如何解决这个问题?

我代码:

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

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

    UISwitch* switchView = (UISwitch *)[cell viewWithTag:5];
    [switchView addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
       return cell;
}

这是因为UITableView重用UITableViewCell,所以一个单元格可以在不同的indexPaths中使用不止一次,在这种情况下,你有责任维护UITableViewCell子视图的状态。更好的地方做到这一点是cellForRowAtIndexPath,你是返回单元格添加逻辑,使显示/隐藏UISwitch或选择准确的状态,即打开或关闭,你可以保持该标志在dataSource对象,然后你可以检查该标志,使UISwitch设置正确的状态

Try This:

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *CellIdentifier = @"CellSetting";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
        cell.textLabel.text = [self.settingsArray objectAtIndex:indexPath.row];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        if ([[self.settingsArray objectAtIndex:indexPath.row] isEqualToString:ROW_PRIVATE_BROWSING])
        {
            self.privateBrowsingSwitch =[[UISwitch alloc]initWithFrame:CGRectMake(cell.frame.size.width-65, 10, 30, 30)];
            if (ApplicationDelegate.privateBrowsing)
            {
                [self.privateBrowsingSwitch setOn:YES animated:YES];
            }
            [self.privateBrowsingSwitch addTarget:self action:@selector(changeSwitch:) forControlEvents:UIControlEventValueChanged];
            [cell addSubview:self.privateBrowsingSwitch];
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
        return cell;
    }

每次调用cellForRowAtIndexPath时,您都必须替换需要在该位置为单元格显示的特定数据。这包括标签,图像和ui开关。

这是因为UITableViews使用了少量被重用的单元格。

在cellForRowAtIndexPath中添加如下内容:

switchView.on = [self isSwitchOnForCellAtIndexPath:indexPath]

然后编写所需的逻辑来确定开关是否应该打开

最新更新