2016-03-04 93 views
4

我在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://stackoverflow.com/questions/29722113/how-to-access-index-path-of-button-in-a-custom-tableviewcell – Shades

+0

謝謝,那應該確實解決它。 –

回答

6

最簡單的解決方案是使用交換機的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

相關問題