[英]If I add a UISwitch control to each of my table view cells, how can I tell which cell it belongs to?
我有一个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
方法时,如何判断它属于哪个表格单元? 如果不了解它的背景,我真的无法做很多事情。
非常感谢您的帮助!
首先,修复内存泄漏:
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
在你的action方法中,你可以转换传入的UISwitch
的indexPathForCell
superview
(它是UITableViewCell
本身),然后将它传递给tableView
的indexPathForCell
方法。
indexPathForCell
将返回一个NSIndexPath
对象,然后您可以使用该对象索引要修改的数据模型。 然后你要做的就是在tableView
上调用reloadData
。
此外,在cellForRowAtIndexPath
,您应该根据您的模型设置UISwitch
的状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.