0

我是 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

4

1 回答 1

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(最后一个 UiSwitch)。

于 2011-03-17T04:23:45.067 回答