如果我将UISwitch控件添加到每个表视图单元格中,如何判断它属于哪个单元格?

Bea*_*red 7 iphone cocoa-touch uiswitch ipad ios

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

替代文字http://epicself.com/wp-content/uploads/2009/04/1-1.jpg

在我的应用程序的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;
Run Code Online (Sandbox Code Playgroud)

我的问题是,当用户切换开关并switchToggled调用该方法时,如何判断它属于哪个表格单元?如果不了解它的背景,我真的无法做很多事情.

非常感谢您的帮助!

mvd*_*vds 9

首先,修复内存泄漏:

UISwitch *switchEnabled = [[[UISwitch alloc] initWithFrame:frameSwitch] autorelease];
Run Code Online (Sandbox Code Playgroud)

然后选择以下选项之一:

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

NSLog(@"switched %d",switch.tag); // to see which switch was toggled
Run Code Online (Sandbox Code Playgroud)

要么

UITableViewCell *parentCell = switchEnabled.superview;
// + some magic to see which cell this actually is
Run Code Online (Sandbox Code Playgroud)


Jac*_*kin 9

在你的操作方法,你可以施放superview传入的的UISwitch(这是UITableViewCell本身),然后传递到tableViewindexPathForCell方法.

indexPathForCell将返回一个NSIndexPath对象,然后您可以使用该对象索引要修改的数据模型.然后你要做的就是打电话reloadData给你tableView.

此外,cellForRowAtIndexPath您应该UISwitch根据您的模型设置状态.

  • 对于仍然发现superview问题的人,有时你需要指向控件的superview的superview,因为控件可能在UITableViewCellContentView中.UITableViewCellContentView的超级视图将是必需的UITableViewCell (5认同)