【问题标题】:UISwitch in Table Cell -- determine selected indexPath表格单元格中的 UISwitch -- 确定选定的 indexPath
【发布时间】:2015-11-21 17:03:23
【问题描述】:

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

开关在被选中或取消选中时使用target-action进行通信:

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

问题在于找出选择了哪个开关。我知道3种方法。每个人都不满意。

1.我可以use tags

switchV.tag = indexPath.row

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

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

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

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

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

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

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

【问题讨论】:

    标签: uitableview uiswitch accessoryview


    【解决方案1】:

    在我看来,方法#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];
       }
      

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

    【讨论】:

      【解决方案2】:

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

      var switchToData=[UISwitch:yourData]()
      

      在 cellForRowAtIndexPath 中:

      switchToData[newSwitch]=myData
      

      在 onChangeSwitch 中

      dataChanged=switchToData[switchChanged]
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-03
        • 2013-04-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-15
        • 2020-09-06
        相关资源
        最近更新 更多