如何使用 swift 在动态表视图中获取 UISwitch 的索引路径?

How to get the indexpath of UISwitch in dynamic tableview using swift?

我正在创建一个在线测试应用程序。在选择主题时,我有一个带 UISwitch 的动态 table 视图。在那个 table 中,我有 10 行中的 10 个主题。我需要找到每个开关的 indexPath 以获取主题名称。

我是 ios 的新手。我需要 swift.

中的答案
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

         //here you can get uiswitch object
}

此代码将在您的 cellForRowAtIndexPath 中

  var subSwitch:UISwitch! //your switch or you can get this by viewWithTag also
            subSwitch.restorationIdentifier = "\(indexPath.row)"
            subSwitch.addTarget(self, action: "swichValueChange:", forControlEvents: UIControlEvents.ValueChanged)

现在获取值更改事件

 func swichValueChange (sender : UISwitch)
    {
       var id:String = sender.restorationIdentifier
    //here you can identify,which Switch is changed
    }

使用这个简单的代码从子视图中查找索引路径

func indexPathForCellContainingView(switch: UISwitch, inTableView tableView:UITableView) -> NSIndexPath? {
    let viewCenterRelativeToTableview = tableView.convertPoint(CGPointMake(CGRectGetMidX(view.bounds), CGRectGetMidY(view.bounds)), fromView:view)
    return tableView.indexPathForRowAtPoint(viewCenterRelativeToTableview)
}