How to call the @selector method from another class

Is it possible to call @selector methods from another class? for example, I make the method "bannerTapped:" and call it from the class "myViewController.m".

myviewcontroller.m:

anotherClass *ac= [[anotherClass alloc]init];

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:ac action:@selector(bannerTapped:)];
singleTap.numberOfTapsRequired = 1;
singleTap.numberOfTouchesRequired = 1;
cell.conversationImageView.tag = indexPath.row;
[cell.conversationImageView addGestureRecognizer:singleTap];
[cell.conversationImageView setUserInteractionEnabled:YES];

anotherClass.m:

-(void)bannerTapped:(UIGestureRecognizer *)gestureRecognizer {
    //do something here 
}

updated :

viewController.m:

 #import "anotherClass.h"



 +(viewcontroller *)myMethod{
 // some code...

 anotherClass *ac= [[anotherClass alloc]init];

    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:ac   action:@selector(bannerTapped:)];

}

anotherClass.h:

-(void)bannerTapped:(UIGestureRecognizer *)gestureRecognizer;

anotherClass.m:

-(void)Viewdidload{
    [viewController myMethod];
     }


   -(void)bannerTapped:(UIGestureRecognizer *)gestureRecognizer {
      //do something here 
   }
+4
source share
3 answers

Yes like that

initWithTarget:anotherClassInstance action:@selector(bannerTapped:)];

Target is the instance of the class to which you want to send the event.

EDIT

Please learn how to publish all of your code in the future, since your FAR question is more complex than you asked. In short, you cannot do this:

+(viewcontroller *)myMethod{

   anotherClass *ac= [[anotherClass alloc]init];

   UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:ac   action:@selector(bannerTapped:)];

}

, ac , , , . ARC .

:

  • +(void) , ac, , .
  • ( ), , , ac viewController, . ac - . , , , .

, . , , , .

objective-c - .

+4

:

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:myViewcontroller action:@selector(bannerTapped:)];

, , , bannerTapped:. anotherClass . , , , .

+1

,

[[UITapGestureRecognizer alloc]initWithTarget: action:];

, . , , , , . , - :

@property (nonatomic, strong) anotherClass *myClass;

And make sure the class is highlighted before passing it to the gesture recognizer, for example:

self.myClass = [[anotherClass alloc[init];
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:self.myClass action:@selector(bannerTapped:)];
//...
+1
source

Source: https://habr.com/ru/post/1526765/


All Articles