如何从外部tableview方法更改UITableViewCell

时间:2013-03-27 14:16:22

标签: uitableview uiswitch

我有一个UITableView,它将UISwitch保存为UITableViewCell accessoryView。enter image description here

我正在尝试创建一个响应交换机更改的方法。 基本上在任何给定的时间内只应打开一个阀门所以当我打开一个开关时我想要它,它将使已经打开的开关切换到关闭状态。

我做了类似的事情:

-(IBAction)openCloseValve:(id)sender

{

UISwitch *theSwitch = (UISwitch *)sender;

if ([theSwitch isOn])

{

    //Open Valve!

    NSLog(@"Opening Valve!");

    Storage *strg = [Storage sharedStorage];



    UITableViewCell *oldCell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:strg.openValve.intValue-1 inSection:0]];

    UISwitch *newSwitch = [[UISwitch alloc] initWithFrame:CGRectZero];

    newSwitch.onTintColor = [UIColor greenColor];

    newSwitch.on = NO;

    oldCell.accessoryView = newSwitch;


    strg.openValve= [[NSNumber alloc] initWithInt:theSwitch.tag + 1];

    NSLog(@"%d", strg.openValve.intValue);

} else {

    //Close Valve!

    NSLog(@"Closing Valve!");

}

}

到目前为止它什么也没做。 我知道这个方法正在调用。 我做错了什么?

1 个答案:

答案 0 :(得分:0)

旧单元格需要通过[tableView reloadCellsAtIndexPath:]进行更新。您可以通过更新旧交换机而不是创建新交换机来避免这种情况:

UISwitch *oldSwitch = (UISwitch *)oldCell.accessoryView;
oldSwitch.on = NO;