Skip to content

Instantly share code, notes, and snippets.

@lamprosg
Last active November 28, 2020 16:25
Show Gist options
  • Select an option

  • Save lamprosg/92bcc3f0bd336c89147e95fcb2cfce4e to your computer and use it in GitHub Desktop.

Select an option

Save lamprosg/92bcc3f0bd336c89147e95fcb2cfce4e to your computer and use it in GitHub Desktop.
(iOS) Swift button tap with handler
class MySwitch: UISwitch {
typealias DidTapSwitch = (WMSwitch) -> ()
var didChangeState: DidTapSwitch? {
didSet {
if didChangeState != nil {
addTarget(self, action: #selector(self.switchStateDidChange(_:)), for: .valueChanged)
} else {
removeTarget(self, action: #selector(self.switchStateDidChange(_:)), for: .valueChanged)
}
}
}
@objc func switchStateDidChange(_ sender: MySwitch) {
if let handler = didChangeState {
handler(self)
}
}
}
@lamprosg
Copy link
Author

lamprosg commented Jun 20, 2018

Use it:

@IBOutlet var smartSwitch: MySwitch!

smartSwitch. didChangeState = { (sender) in
    ......
}

Remove action

smartSwitch.didChangeState = nil

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment