Swift/UISwitch: how to implement a delegate/listener

后端 未结 7 1727
慢半拍i
慢半拍i 2020-12-29 19:24

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

import Foundation
import UIKit

class SwitchCell: UITableV         


        
7条回答
  •  旧巷少年郎
    2020-12-29 20:19

    Swift 3:

    Using Storyboard Autolayout:

    Add Reference:

    @IBOutlet weak var sampleSwitch: UISwitch!
    

    Associate method:

    @IBAction func sampleSwitchValueChanged(_ sender: Any) {
    
        if sampleSwitch.isOn {
            print("ON")  
        }
        else {
            print ("OFF")
        }
    }
    

    Programatic way:

    Adding Target:

    sampleSwitch.addTarget(self, action: #selector(ViewController.sampleSwitchValueChanged(sender:)), for: UIControlEvents.valueChanged)
    

    The method associated with the switch:

       func sampleSwitchValueChanged(sender: UISwitch!)
        {
            if sender.isOn {
    
                print("switch on")
    
            } else {
    
            }
        }
    

提交回复
热议问题