如何动态更改UITableView的UISwitch?

时间:2012-11-25 00:38:40

标签: iphone ios uitableview delegates uiswitch

我有一个UItableView,其中每个UITableViewCell都包含一个UISwitch。现在我的问题是,当我点击一个切换时,我怎么能OFF其他切换UITableViewCell

在我的代码中,我已经创建了视图,我可以ON/OFF切换。但我想OFF除了我选择的切换之外的所有其他开关。

请一些示例或源代码示例帮助我。

最诚挚的问候

修改

我的代码:

- (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] autorelease];
        switchview = [[UISwitch alloc] initWithFrame:CGRectZero];
        cell.accessoryView = switchview;
        switchCondition = NO;
        [switchview setOn:NO animated:YES];
        [switchview addTarget:self action:@selector(updateSwitchAtIndexPath:) forControlEvents:UIControlEventValueChanged];
        [switchview release];
    }
    if(switchCondition == YES){
    [switchview setOn:YES animated:YES];
    }

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.contentView.backgroundColor = [UIColor clearColor];
    cell.textLabel.text = [NSString stringWithFormat:@"%@",[cellValueArray objectAtIndex:indexPath.row]];
    return cell;
}

- (void)updateSwitchAtIndexPath:(UISwitch*)sender {
    if(sender.on){
        switchCondition = YES;
        [table reloadData];
    }
}

1 个答案:

答案 0 :(得分:1)

更新表数据源使用的数据模型,然后重新加载表(或至少可见行)。这将导致每行重新加载,每个开关将使用最新数据进行更新。

编辑:这是您的代码的更新版本:

您需要一个实例变量来跟踪每个开关的状态。创建一个数组以保存YES和NO值。在下面的代码中,我将假设有一个名为switchConditions的{​​{1}}类型的实例变量已经设置了NSMutableArray个对象,表示每行的YES和NO值。这与您的NSNumber类似。您还应该删除cellValueArrayswitchView实例变量。

switchCondition
相关问题