【问题标题】:identifying a UISwitch in UITableViewCell在 UITableViewCell 中识别 UISwitch
【发布时间】: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/…
  • 谢谢,这确实应该解决它。

标签: ios swift swift2 uiswitch


【解决方案1】:

最简单的解决方案是使用开关的tag 属性。创建开关时,分配一个标签

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

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

func switchTriggered(sender: AnyObject) {

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

【讨论】:

  • lightSwitch 有 10 个(因为 tableViewCell 有 10 个),这如何帮助识别按下的是哪个开关?
  • 只需将indexPath.row 分配为开关的tag。你会知道哪个开关,在哪一行,以这种方式被激活的。
  • 比我提到的+1更好的答案
  • 哦,那样!是的,这确实很好用!非常感谢你!这是一个巨大的帮助。有时我觉得很有趣,我无法解决如此简单的事情,但确实可以制作一些非常复杂的应用程序..
  • 虽然扩展很方便跟踪 Int 以外的值
猜你喜欢
  • 2011-04-22
  • 1970-01-01
  • 1970-01-01
  • 2020-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多