Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.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
Uitableview 表单元格中的UISwitch--确定选定的indexPath_Uitableview_Uiswitch_Accessoryview - Fatal编程技术网

Uitableview 表单元格中的UISwitch--确定选定的indexPath

Uitableview 表单元格中的UISwitch--确定选定的indexPath,uitableview,uiswitch,accessoryview,Uitableview,Uiswitch,Accessoryview,我正在UITableViewCell的accessoryView中使用UISwitch 选择或取消选择时,开关使用目标动作进行通信: switchV.addTarget(self, action: "onChangeSwitch:", forControlEvents: UIControlEvents.ValueChanged) 问题在于确定选择了哪个开关。我知道三种方法。每个人都有不满意的地方 1.我可以: 但是如果你有节(我也有),这很糟糕,因为我需要将它解析成两个数字的节/行格式 2。我

我正在UITableViewCell的accessoryView中使用UISwitch

选择或取消选择时,开关使用目标动作进行通信:

switchV.addTarget(self, action: "onChangeSwitch:", forControlEvents: UIControlEvents.ValueChanged)
问题在于确定选择了哪个开关。我知道三种方法。每个人都有不满意的地方

1.我可以:

但是如果你有节(我也有),这很糟糕,因为我需要将它解析成两个数字的节/行格式

2。我可以使用数据模型并将开关视图存储在单元格正在绘制的数据项上:

dataItem.switch.addTarget(self, action: "onChangeSwitch:", forControlEvents: UIControlEvents.ValueChanged)
cell.accessoryView = dataItem.switch
然后,我可以通过在我的数据集上循环并与发送者进行身份匹配来确定选择了哪个交换机。这是一个很大的循环,我不想把视图放在我的数据模型中

3.然后是一个使用开关坐标来查找行的函数。无状态ish,不涉及字符串解析或数据模型混淆,而是坐标,rly?我能相信吗

tableView.indexPathForRowAtPoint(
  sender.convertPoint(CGPointZero, toView: tableView)
)
有没有更好的方法来获取所选UISwitch的indexPath?

方法#3在我看来相当不错。不过,如果你想让它真正干净,我会这么做

  • 声明一个自定义TableviewCell,比如CustomTableViewCell,并具有一个名为CustomCellDelegate的委托协议。在这里,学员会得到如下通知:

     -(void)switchChanged:(UISwitch*)switch inCell:(CustomTableViewCell*)cell
    
  • 在cellForRowAtIndexPath中,将视图控制器设置为单元格的代理

  • 将开关添加到自定义单元格,并将该单元格作为目标并实现开关的操作方法。在action方法内调用委托:

    -(void)switchChanged:(id)sender {
        if(self.delegate && [self.delegate respondsToSelector:@selector(switchChanged:inCell:])) {
            [self.delegate switchChanged:sender inCell:self];
    }
    
  • 现在,在viewController中,使用委托方法中传入的单元格计算索引路径:

     -(void)switchChanged:(id)sender inCell:(CustomTableViewCell*)cell {
        NSIndexPath *path = [self.tableview indexPathForCell:cell];
     }
    

这需要做一点工作,但是如果你想用正确的方法来做,你可以。

另一个选择是使用一个散列来维护开关->数据链接

var switchToData=[UISwitch:yourData]()
在cellForRowAtIndexPath中:

switchToData[newSwitch]=myData
在线交换开关

dataChanged=switchToData[switchChanged]
散列将非常小,与可见开关的大小相同

dataChanged=switchToData[switchChanged]