在UITableViewCell中识别UISwitch

Bra*_*dts 4 uiswitch ios swift swift2

我在UITableViewCell中实现UISwitch时遇到了一些麻烦.我的tableViewCell:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell

{

    let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")


    cell.textLabel?.text = "Hello Magic Switch buyers!"
    cell.textLabel?.textColor = UIColor.whiteColor()
    cell.backgroundColor = UIColor.clearColor()

    lightSwitch = UISwitch(frame: CGRectZero) as UISwitch
    lightSwitch.on = false
    lightSwitch.addTarget(self, action: "switchTriggered", forControlEvents: .ValueChanged );



    cell.accessoryView = lightSwitch

    return cell
}
Run Code Online (Sandbox Code Playgroud)

这创建了开关,一切正常,直到函数被调用为止.你通常用例如一个按钮,只是使用它的indexPath.row来区分所有单元格,但因为这是一个配件视图,我无法让这个工作!switchTriggered函数:

func switchTriggered() {



    if lightSwitch.on {

        let client:UDPClient = UDPClient(addr: "192.168.1.177", port: 8888)
        let (_) = client.send(str: "HIGH" )
        print(String(indexPath.row) + " set to high")

    } else {
        let client:UDPClient = UDPClient(addr: "192.168.1.177", port: 8888)
        let (_) = client.send(str: "LOW" )
        print(String(indexPath.row) + " set to low")
    }

}
Run Code Online (Sandbox Code Playgroud)

该函数不知道哪个lightSwitch被切换以及indexPath是什么..我怎么能解决这个问题?如果它是一个按钮,我可以使用,accessoryButtonTappedForRowWithIndexPath但事实并非如此.

一些帮助将不胜感激,因为TableViewCells中有关UISwitch的所有信息都在Objective-C中.

非常感谢你!

Raf*_*fAl 8

最简单的解决方案是使用tag交换机的属性.创建开关时,请指定标签

lightSwitch = UISwitch(frame: CGRectZero) as UISwitch
lightSwitch.tag = 2000
lightSwitch.addTarget(self, action: Selector("switchTriggered:"), forControlEvents: .ValueChanged );
Run Code Online (Sandbox Code Playgroud)

然后修改您的处理程序方法以具有sender参数

func switchTriggered(sender: AnyObject) {

    let switch = sender as! UISwitch
    if switch.tag == 2000 {
        // It's the lightSwitch
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 只需将 `indexPath.row` 指定为开关的 `tag`。您将知道以这种方式激活了哪一行中的哪个开关。 (3认同)
  • 哦那样!是的,这确实很好用!非常感谢你!这是一个巨大的帮助.我发现有趣的是有时我无法解决这些简单的事情,但确实做了一些相当复杂的应用程序.. (2认同)