在UITableViewCell中标识UISwitch

问题描述:

我在UITableViewCell中实现UISwitch时遇到了一些麻烦。我tableViewCell:在UITableViewCell中标识UISwitch

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 
} 

这产生了开关,一切正常,直到点函数被调用..你通常会使用例如按钮,只是使用它的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") 
    } 

} 

功能不知道哪个LightSwitch的切换了,indexPath是什么。我怎么能解决这个问题?如果是按钮,我可以使用accessoryButtonTappedForRowWithIndexPath,但事实并非如此。

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

非常感谢!

+0

我不知道是否有一个更好的(阅读:内置)的方式做它,但我喜欢,并已实施,在这里接受的答案:http://*.com/questions/29722113/how-to-access-index-path-of-button-in-a-custom-tableviewcell – Shades

+0

谢谢,那应该确实解决它。 –

最简单的解决方案是使用交换机的tag属性。当创建开关,分配标签

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

然后修改你的处理方法有一个参数sender

func switchTriggered(sender: AnyObject) { 

    let switch = sender as! UISwitch 
    if switch.tag == 2000 { 
     // It's the lightSwitch 
    } 
} 
+0

有10个lightSwitches(因为有10个tableViewCells),它如何帮助识别它被按下的开关? –

+1

只需将'indexPath.row'指定为交换机的'标签'即可。您将知道哪个开关在哪个行中以这种方式被激活。 – RaffAl

+0

比我引用的更好的答案+1 – Shades