繁体   English   中英

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

[英]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方法中,你可以转换传入的UISwitchindexPathForCell superview (它是UITableViewCell本身),然后将它传递给tableViewindexPathForCell方法。

indexPathForCell将返回一个NSIndexPath对象,然后您可以使用该对象索引要修改的数据模型。 然后你要做的就是在tableView上调用reloadData

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM