Lory Lory Lory Lory - 5 months ago 27
Swift Question

Swift/UISwitch: how to implement a delegate/listener

In my UITableViewController I have a custom cell which contains a switcher whoce is the following:

import Foundation
import UIKit

class SwitchCell: UITableViewCell {
@IBOutlet weak var label : UILabel!
@IBOutlet weak var switchEmail : UISwitch!

func setEditable(canEdit:Bool) {
if (canEdit) {
self.switchEmail.enabled = true
self.label.highlighted = false
else {
self.switchEmail.enabled = false
self.label.highlighted = true

func configureCellWithSwitch(labelText:String, switchValue:Bool, enabled:Bool) {

var labelFrame:CGRect = self.label.frame
labelFrame.size.height = Settings.labelHeight
self.label.frame = labelFrame

self.label.text = labelText

if (switchValue) {
self.switchEmail.setOn(true, animated: true)
else {
self.switchEmail.setOn(false, animated: true)



I would like to know how to implement a listener/delegate to the switcher in order to get its value from the UITableViewController. I was able to write delegate/listeners for cell with UITextField and UITextView implementing the methods

func controller(controller: UITableViewCell, textViewDidEndEditing: String, atIndex: Int)


func controller(controller: UITableViewCell, textFieldDidEndEditingWithText: String, atIndex: Int)

but I don't know what I should implement for the switcher.


UISwitch has no delegate protocol. You can listen to the status as follows:


// somewhere in your setup:
[self.mySwitch addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];

- (void)switchChanged:(UISwitch *)sender {
   // Do something
   BOOL value = sender.on;


mySwitch.addTarget(self, action: "switchChanged:", forControlEvents: UIControlEvents.ValueChanged)

func switchChanged(mySwitch: UISwitch) {
   let value = mySwitch.on
   // Do something