[英]If I add a UISwitch control to each of my table view cells, how can I tell which cell it belongs to?
I have a UITableView
with cells that contain a UISwitch
control. 我有一个
UITableView
与包含UISwitch
控件的单元格。 It's similar to the table view in the iPhone's Clock app shown below... 它类似于下面显示的iPhone时钟应用程序中的表格视图......
(source: epicself.com ) (来源: epicself.com )
In my app's cellForRowAtIndexPath
method, I create and attach the UISwitch
control like so... 在我的应用程序的
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;
My question is, when the switch is toggled by the user and the switchToggled
method is called, how can I tell which table cell it belongs to? 我的问题是,当用户切换开关并调用
switchToggled
方法时,如何判断它属于哪个表格单元? I can't really do much with it without knowing it's context. 如果不了解它的背景,我真的无法做很多事情。
Thanks so much in advance for your help! 非常感谢您的帮助!
First of all, fix the memory leak: 首先,修复内存泄漏:
UISwitch *switchEnabled = [[[UISwitch alloc] initWithFrame:frameSwitch] autorelease];
Then pick one of these options: 然后选择以下选项之一:
switchEnabled.tag = someInt; // before adding it to the cell
NSLog(@"switched %d",switch.tag); // to see which switch was toggled
or 要么
UITableViewCell *parentCell = switchEnabled.superview;
// + some magic to see which cell this actually is
In your action method, you can cast the superview
of the passed-in UISwitch
(which is the UITableViewCell
itself), then pass that to the tableView
's indexPathForCell
method. 在你的action方法中,你可以转换传入的
UISwitch
的indexPathForCell
superview
(它是UITableViewCell
本身),然后将它传递给tableView
的indexPathForCell
方法。
indexPathForCell
will return a NSIndexPath
object, which you can then use to index to your datamodel to modify. indexPathForCell
将返回一个NSIndexPath
对象,然后您可以使用该对象索引要修改的数据模型。 Then all you gotta do is call reloadData
on your tableView
. 然后你要做的就是在
tableView
上调用reloadData
。
Also, in cellForRowAtIndexPath
, you should set the UISwitch
's state based on your model. 此外,在
cellForRowAtIndexPath
,您应该根据您的模型设置UISwitch
的状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.