Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want a global function which call on every button click in my whole application. What should be a short trick for this?

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.

like image 359
saurabh mangal Avatar asked May 02 '16 09:05

saurabh mangal


2 Answers

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

like image 136
Prajeet Shrestha Avatar answered Oct 16 '22 16:10

Prajeet Shrestha


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/

like image 32
Mert Buran Avatar answered Oct 16 '22 15:10

Mert Buran