我在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中。
非常感謝!
我不知道是否有一個更好的(閱讀:內置)的方式做它,但我喜歡,並已實施,在這裏接受的答案:http://stackoverflow.com/questions/29722113/how-to-access-index-path-of-button-in-a-custom-tableviewcell – Shades
謝謝,那應該確實解決它。 –