Switch 中 TableView 中的 UISwitch

UISwitch in TableView in Switch

各位程序员大家好!我有一个挑战需要帮助。我使用自定义样式单元构建了一个 table。

这个单元格只有 LabelUISwitch。标签显示名称,开关显示他们是否是管理员。这非常有效。我的挑战是当开关改变时,我如何以及在哪里放置代码以做出反应。

所以,如果我单击开关将其从关闭更改为打开,我在哪里可以得到它来打印人员姓名?如果我能得到要打印的名称,我就可以自己编写 php/sql 代码。谢谢,这是我的代码片段。

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier) as UITableViewCell
    let admin = self.admin[indexPath.row]

    let text1a = admin.FirstName
    let text1aa = " "

    let text1b = admin.LastName
    let text1 = text1a + text1aa + text1b
    (cell.contentView.viewWithTag(1) as UILabel).text = text1

    if admin.admin == "yes" {
        (cell.contentView.viewWithTag(2) as UISwitch).setOn(true, animated:true)

    } else if admin.admin == "no" {
        (cell.contentView.viewWithTag(2) as UISwitch).setOn(false, animated:true)
    }

    return cell
}

你需要监听 UISwitch 的 .ValueChanged,在 YOUR_CUSTOM_CELL 中做出一些决定。在那里你可以捕捉到 "println" 你的数据。

埃里克,

在 table 视图生命周期的某个时刻,您需要使用 target/action.

配置 table 单元格中的每个 UISwitch

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIControl_Class/index.html#//apple_ref/occ/instm/UIControl/addTarget:action:forControlEvents:

action 告诉 UISwitch 实例当用户翻转开关时它应该调用什么方法。 target 告诉 UISwitch 实例托管该方法的对象。

通常,您将使用 UITableViewController(或 UIViewController)子类作为目标。

您必须在自定义 Table View Cell 中设置一个 action 来处理 UISwitch 中的变化并对其中的变化做出反应,请参阅以下代码:

class CustomTableViewCell: UITableViewCell {

     @IBOutlet weak var label: UILabel!

     @IBAction func statusChanged(sender: UISwitch) {
         self.label.text = sender.on ? "On" : "Off"
     }
}

上面的例子只是用来改变UILabel的文本关于UISwitch的状态,当然你必须根据你的要求改变它。希望对你有帮助。