UISwitch in TableView in Switch

笑着哭i 提交于 2019-12-06 04:08:15

问题


Hello fellow programmers! I have a challenge I need help with. I have built a table using a Custom Style Cell.

This cell simply has a Label and UISwitch. The label displays a name and the switch displays whether they are an Admin or not. This works perfectly. My challenge is how and where do I put code to react when the switch is changed.

So if I click the switch to change it from off to on where can I get it to print the persons name? If I can get the name to print I can do the php/sql code myself. Thanks and here is a snippet from my code.

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
}

回答1:


You have to set an action in your Custom Table View Cell to handle the change in your UISwitch and react to changes in it, see the following code :

class CustomTableViewCell: UITableViewCell {

     @IBOutlet weak var label: UILabel!

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

The above example is just used to change the text of the UILabel regarding the state of the UISwitch, you have to change it in base your requirements of course. I hope this help you.




回答2:


You need to listen .ValueChanged of UISwitch, in YOUR_CUSTOM_CELL to make some decisions. There you can catch to "println" your data.




回答3:


Eric,

At some point in the tableview's lifecycle, you'll need to configure each UISwitch in the table cell with a target/action.

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

The action tells the UISwitch instance what method it should invoke when the switch is flipped by the user. The target tells the UISwitch instance what object is hosting that method.

Typically, you'll use the UITableViewController (or UIViewController) subclass as the target.



来源:https://stackoverflow.com/questions/29354969/uiswitch-in-tableview-in-switch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!