7

我有一个UITableView包含UISwitch控件的单元格。它类似于下面显示的 iPhone 时钟应用程序中的表格视图......

替代文字
(来源:epicself.com

在我的应用程序的cellForRowAtIndexPath方法中,我像这样创建并附加UISwitch控件......

 CGRect frameSwitch = CGRectMake(215.0, 10.0, 94.0, 27.0);
 UISwitch *switchEnabled = [[UISwitch alloc] initWithFrame:frameSwitch];
 [switchEnabled addTarget:self action:@selector(switchToggled:) forControlEvents:UIControlEventValueChanged];

 cell.accessoryView = switchEnabled;

我的问题是,当用户切换开关并switchToggled调用方法时,我怎么知道它属于哪个表格单元格?如果不知道它的上下文,我真的不能用它做很多事情。

非常感谢您的帮助!

4

2 回答 2

9

首先,修复内存泄漏:

UISwitch *switchEnabled = [[[UISwitch alloc] initWithFrame:frameSwitch] autorelease];

然后选择以下选项之一:

switchEnabled.tag = someInt; // before adding it to the cell

NSLog(@"switched %d",switch.tag); // to see which switch was toggled

或者

UITableViewCell *parentCell = switchEnabled.superview;
// + some magic to see which cell this actually is
于 2010-08-11T20:27:45.637 回答
9

在您的操作方法中,您可以转换superview传入的UISwitch(它UITableViewCell本身),然后将其传递给tableView'indexPathForCell方法。

indexPathForCell将返回一个NSIndexPath对象,然后您可以使用它来索引您的数据模型以进行修改。那么你所要做的就是调用reloadData你的tableView.

此外,在 中cellForRowAtIndexPath,您应该UISwitch根据您的模型设置 ' 状态。

于 2010-08-11T20:29:02.590 回答