I want a global function which call on every button click in my whole application. What should be a short trick for this?
I have tried many things like override add target method etc. button no luck yet. Let me know if i am unclear.
This is a good question!
Just make an extension like this:
extension UIButton {
override public func awakeFromNib() {
super.awakeFromNib()
self.addTarget(self, action: #selector(methodTobeCalledEveryWhere), forControlEvents: .TouchUpInside)
}
func methodTobeCalledEveryWhere () {
print("HEY, I M EVERY WHERE!")
}
}
Add this extension anywhere it should be in file scope though. It will make all the buttons in the the module (Module in which this extension resides) trigger the method methodTobeCalledEveryWhere.
NOTE: This is for Swift 2.2
you should write your own UIButton
category/extension and you should swizzle beginTrackingWithTouch:withEvent method with your own method. When any UIButton
instance calls its beginTrackingWithTouch
method, your method will be called since you already swizzled it, thus you can perform any additional action every time a button is being tapped.
In fact beginTrackingWithTouch:
is a UIControl
method, so you can listen to all UIControl
instances by writing your UIControl
category/extension too.
A good read for more information about swizzling: http://nshipster.com/method-swizzling/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With