如何使用标记属性检查具有自定义单元格的表视图中的多个UISwitch控件的状态

我有一个自定义UITableViewCell的tableview。 Cell有一个UISwitch控件。 我已经添加单元到表视图控制器与所有开关相同的操作。 我在cellForRowAtIndexPath方法中添加了UISwitch标签值。

我想确定什么开关被改变,当用户改变开关状态的开/关。 这里我正在设置UISwitchbutton的操作。

 - (void)viewDidLoad { [super viewDidLoad]; cell.switchbtn.userInteractionEnabled=YES; [cell.switchbtn setOn:YES]; [cell.switchbtn addTarget:self action:@selector(switchToggled:) forControlEvents: UIControlEventValueChanged]; [cell.contentView addSubview:cell.switchbtn]; } 

这里我正在设置uiswitch的标签值

 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellidentifier=@"cellid"; cell=[tableView dequeueReusableCellWithIdentifier:cellidentifier]; if (!cell) { [[NSBundle mainBundle] loadNibNamed:@"cellid" owner:self options:nil]; } cell.switchbtn.tag=indexPath.row; NSLog(@"btn tag=%d",cell.switchbtn.tag); return cell; } 

在这里,我打电话给switchToggled:方法来获得uiswitch状态。

 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath; { [self switchToggled:cell.switchbtn]; } 

我得到的标签值和每一次的状态是在。即使我的状态是closures的。

 - (void) switchToggled:(UISwitch *)sender { UISwitch *mySwitch = (UISwitch *)sender; NSLog(@"tag ==%@",mySwitch); if ([mySwitch isOn]) { NSLog(@"its on!"); } else { NSLog(@"its off!"); } } 

使用CGpoint与直接单元格的属性来确定哪一行被选中,单元格的Uiswitch的状态,你可以更容易地识别更准确,这是我正在使用的一种方法,它对我来说工作正常。

 - (void)switchToggled:(id)sender { CGPoint switchPositionPoint = [sender convertPoint:CGPointZero toView:[self tableName]]; NSIndexPath *indexPath = [[self tableName] indexPathForRowAtPoint:switchPositionPoint]; BusinessHoursCell *cell = (BusinessHoursCell*)[self.tableName cellForRowAtIndexPath:indexPath]; int tag=indexPath.row; if (tag==0) { if (cell.workingDaySwitch.on) { NSLog(@"its on!"); } else { NSLog(@"its off!"); } } } 

我会使用以下scheme:在cellForRowAtIndexPath:..将当前indexPath设置为单元格。 使用方法创build协议- (void)cellAtIndexPath:(NSIndexPath *)path changedSwitchStateToState:(BOOL)state为控制器委派单元格。 单元通过调用委托方法来处理切换状态的变化。

在控制器中,您应该使用dataSource(可能是自定义类)的东西,它存储用于configuration单元格的对象,并具有类似于- (void)changeSwitchStateToState:(BOOL)state atIndexPath:(NSIndexPath *)path ,对象和更新状态。