Swift/UISwitch: how to implement a delegate/listener

后端 未结 7 1658
慢半拍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:21

    Another (Swift 3 or 4) method is to use didSet observer and drastically reduce code, like so-

    In the class declaration declare a variable like below:

    var switchFlag: Bool = false {
            didSet{               //This will fire everytime the value for switchFlag is set
                print(switchFlag) //do something with the switchFlag variable
            }
        }
    

    Then you can have an IBAction on the UISwitch like so

    @IBAction func switchChanged(_ sender: Any) {
            if self.mySwitch.isOn{
                switchFlag = true
            }else{
                switchFlag = false
            }
        }
    
    0 讨论(0)
提交回复
热议问题