2010-08-11 32 views
7

我有一个UITableView与单元格包含UISwitch控件。它类似于在iPhone的时钟应用如下表视图...如果我将UISwitch控件添加到每个表格视图单元格中,我如何知道它属于哪个单元格?

alt text 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; 

我的问题是,当用户切换开关并调用switchToggled方法时,如何知道它属于哪个表格单元?如果不知道它的背景,我无法真正做到。

非常感谢提前对你的帮助!

回答

9

在你的操作方法,你可以投传入的UISwitch(这是UITableViewCell本身)的superview,然后通过即到tableViewindexPathForCell方法。

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

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

+1

这实际上是一个更好的方法,因为它没有使用标签属性,这通常是可用的好东西,谢谢! – BeachRunnerFred 2010-09-05 01:59:18

+5

只为那些仍然在superview中发现问题的人,有时您需要指向控件的超级视图的超级视图,因为控件可能位于UITableViewCellContentView中。 UITableViewCellContentView的超级视图将是必需的UITableViewCell – mrd3650 2012-04-04 16:13:09

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 
+0

用于'.tag'的+1。这是最简单的方法。用索引加载到您填充表格的数据数组中。 – 2010-08-11 20:29:09

+0

谢谢,mvds!标签属性将很好地做!没有泄漏,我只是忘记在问题中包含我的发布呼叫。 – BeachRunnerFred 2010-08-11 20:31:10

相关问题