Search code examples
iosobjective-cobjective-c-category

How I can override addTarget method of UIButton in objective c


I want the same action of UIButton TouchUpInside control event. For example:

[button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];

I want to generalize the buttonAction through out the application. What is the best approach to do this. Is this possible using Categories? Or subclassing?

Thanks in advance.


Solution

  • You can add this method inside class and put the class name into target.

    YourClass *class = [YouClass alloc]init];
    [button addTarget:class action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    

    or you can get the class using accessor like this

    [button addTarget:[A getClassA] action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    @implementation A
      +(YouClass *) getClassA{
        //get instance if already initialized or init it
        //and return the instance
      }
    @end