单击UITwell打开时确定UISwitch的状态

时间:2011-03-17 03:54:21

标签: uitableview uiswitch didselectrowatindexpath

我是IOS编程的新手,我遇到了问题。我有一个表视图,我使用cellForRowAtIndexPath中的以下代码在每个单元格中使用UISwitch动态加载

UISwitch *mySwitch = [[UISwitch alloc]init];
self.myNewSwitch = mySwitch;
[mySwitch release];
[cell setAccessoryView: self.myNewSwitch];
[(UISwitch *)cell.accessoryView addTarget:self action:@selector(changeState:) forControlEvents:UIControlEventValueChanged];

工作正常。当我点击开关时,changeState中的代码运行正常。

这就是我的问题所在。当用户按下表格中的单元格时,我想查看交换机处于什么状态(开或关)。我的问题是我无法弄清楚如何在didSelectRowAtIndexPath代码中确定它。我可以确定正确的单元格,但是当我使用Google搜索时,我无法找到如何访问该单元格上的开关。这是我的didSelectRowAtIndexPath代码:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    //If the on/off switch is on, go to the probes page.  if off, do not do anything
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

   //Determine the switch state here.    
    UISwitch *theSwitch;
    theSwitch = ???????  //<- What do I do???

    if (theSwitch.isOn) {
      //define the probes view controller
      Probes *detailViewController = [[Probes alloc] initWithNibName:@"Probes" bundle:nil];
      //pass in the ip address
      detailViewController.lblIPAddr = cell.detailTextLabel.text;

    // Pass the selected object to the new view controller.
      [self.navigationController pushViewController:detailViewController animated:YES];
      [detailViewController release];
    }
    //Deselect this row
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

任何帮助/代码都会有所帮助。

-NCGrimbo

1 个答案:

答案 0 :(得分:2)

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    //If the on/off switch is on, go to the probes page.  if off, do not do anything
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

   //Determine the switch state here.         

    UISwitch *theSwitch = (UISwitch *)cell.accessoryView ;       

    if (theSwitch.isOn) {
      //define the probes view controller
      Probes *detailViewController = [[Probes alloc] initWithNibName:@"Probes" bundle:nil];
      //pass in the ip address
      detailViewController.lblIPAddr = cell.detailTextLabel.text;

    // Pass the selected object to the new view controller.
      [self.navigationController pushViewController:detailViewController animated:YES];
      [detailViewController release];
    }
    //Deselect this row
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

但我不知道你为什么使用,

UISwitch *mySwitch = [[UISwitch alloc]init];
self.myNewSwitch = mySwitch;
[mySwitch release];
[cell setAccessoryView: self.myNewSwitch];

每次创建新的UITableViewCell时,self.myNewSwitch都是相同的UISwitch(Last UiSwitch)。