Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift/UISwitch: how to implement a delegate/listener

In my UITableViewController I have a custom cell which contains a switcher which 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)     }      self.setEditable(enabled)    } } 

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 a cell with UITextField and UITextView implementing the methods

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

and

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

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

like image 514
SagittariusA Avatar asked Sep 15 '15 13:09

SagittariusA


2 Answers

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

ObjC:

// somewhere in your setup: [self.mySwitch addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];   - (void)switchChanged:(UISwitch *)sender {    // Do something    BOOL value = sender.on; } 

Swift:

mySwitch.addTarget(self, action: "switchChanged:", forControlEvents: UIControlEvents.ValueChanged)  func switchChanged(mySwitch: UISwitch) {    let value = mySwitch.on    // Do something } 

Swift3 :

mySwitch.addTarget(self, action: #selector(switchChanged), for: UIControlEvents.valueChanged)  func switchChanged(mySwitch: UISwitch) {     let value = mySwitch.isOn     // Do something } 

Swift4:

mySwitch.addTarget(self, action: #selector(switchChanged), for: UIControl.Event.valueChanged)  @objc func switchChanged(mySwitch: UISwitch) {     let value = mySwitch.isOn     // Do something } 
like image 61
dibi Avatar answered Oct 11 '22 19:10

dibi


In Swift4.0

mySwitch.addTarget(self, action: #selector(valueChange), for:UIControlEvents.valueChanged)   @objc func valueChange(mySwitch: UISwitch) {         let value = mySwitch.isOn         // Do something         print("switch value changed \(value)")     } 
like image 25
Mujahid Latif Avatar answered Oct 11 '22 19:10

Mujahid Latif