Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/iphone/38.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/xamarin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Iphone 如果我将UISwitch控件添加到每个表视图单元格中,如何知道它属于哪个单元格?_Iphone_Cocoa Touch_Ipad_Ios_Uiswitch - Fatal编程技术网

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

Iphone 如果我将UISwitch控件添加到每个表视图单元格中,如何知道它属于哪个单元格?,iphone,cocoa-touch,ipad,ios,uiswitch,Iphone,Cocoa Touch,Ipad,Ios,Uiswitch,我有一个UITableView,其中的单元格包含UISwitch控件。它类似于下面显示的iPhone时钟应用程序中的表视图 (来源:) 在我的应用程序的cellforrowatinexpath方法中,我创建并附加UISwitch控件,如下所示 CGRect frameSwitch = CGRectMake(215.0, 10.0, 94.0, 27.0); UISwitch *switchEnabled = [[UISwitch alloc] initWithFrame:frameSwit

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


(来源:)

在我的应用程序的
cellforrowatinexpath
方法中,我创建并附加
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


在您的操作方法中,您可以强制转换传入的
UISwitch
(即
UITableViewCell
本身)的
superview
,然后将其传递给
tableView
indexPathForCell
方法

indexPathForCell
将返回一个
nsindepath
对象,然后您可以使用该对象索引到要修改的数据模型。然后,您所要做的就是调用
表视图上的
重新加载数据


此外,在
单元格中,您应该根据您的型号设置
UI开关的状态。

+1表示
.tag
。这是最简单的方法。将其与索引一起加载到填充表的数据数组中。谢谢,mvds!tag属性将很好地工作!没有泄漏,我只是忘了在问题中包含我的发布调用。这实际上是一个更好的方法,因为它不会使用标记属性,这通常是一个好东西,谢谢!对于那些仍然发现superview有问题的用户,有时您需要指向控件的superview的superview,因为控件可能位于UITableViewCellContentView中。UITableViewCellContentView的superview将是必需的UITableViewCell
UITableViewCell *parentCell = switchEnabled.superview;
// + some magic to see which cell this actually is