【发布时间】:2016-03-04 21:09:29
【问题描述】:
我在 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
}
这将创建开关,一切正常,直到调用函数为止。您通常会使用例如按钮执行的操作只是使用它的 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 中有关 UISwitches 的所有信息都在 Objective-C 中。
非常感谢!
【问题讨论】:
-
我不知道是否有更好的(阅读:内置)方法来做到这一点,但我喜欢并已经实施了这里接受的答案:stackoverflow.com/questions/29722113/…
-
谢谢,这确实应该解决它。