3

我在 UITableViewCell 的附件视图中使用了 UISwitch。

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

switchV.addTarget(self, action: "onChangeSwitch:", forControlEvents: UIControlEvents.ValueChanged)

问题在于确定选择了哪个开关。我知道3种方法。不知何故,每个人都不满意。

1.我可以使用标签

switchV.tag = indexPath.row

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

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

dataItem.switch.addTarget(self, action: "onChangeSwitch:", forControlEvents: UIControlEvents.ValueChanged)
cell.accessoryView = dataItem.switch

然后,我可以通过遍历我的数据集并与发件人进行身份匹配来确定选择了哪个开关。这是很多循环,我不想将视图放在我的数据模型中。

3.然后就是使用开关的坐标来查找行的这个方法。无状态,不涉及字符串解析或数据模型混淆,但坐标,rly?我可以相信它吗?

tableView.indexPathForRowAtPoint(
  sender.convertPoint(CGPointZero, toView: tableView)
)

有没有更好的方法来获取所选 UISwitch 的 indexPath?

4

2 回答 2

4

方法#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];
     }
    

它有点工作,但如果你想以正确的方式做到这一点,你可以。

于 2015-08-27T12:57:51.487 回答
1

另一种选择是使用维护交换机 -> 数据链接的哈希

var switchToData=[UISwitch:yourData]()

在 cellForRowAtIndexPath 中:

switchToData[newSwitch]=myData

在 onChangeSwitch

dataChanged=switchToData[switchChanged]

散列将非常小,与可见开关的大小相同......

于 2015-08-27T13:06:53.990 回答