5

是否可以从另一个类调用@selector 方法?例如,我创建了一个方法“bannerTapped:”并从“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];

另一个类.m:

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

更新

视图控制器.m:

 #import "anotherClass.h"



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

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

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

}

另一个类.h:

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

另一个类.m:

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


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

4 回答 4

6

是的,像这样

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

Target是您要将事件发送到的类实例。

编辑

请学习在将来发布您的所有代码,因为您的问题比您所要求的要复杂得多。长话短说你不能这样做:

+(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和面向对象编程,然后再试一次。

于 2014-02-13T15:22:29.453 回答
1

是的,您可以从目标参数

[[UITapGestureRecognizer alloc]initWithTarget: action:];

指定要运行选择器的类。您应该记住的一件事是需要分配您的 anotherClass 并且它应该保持强引用。所以最好的方法是创建属性:

@property (nonatomic, strong) anotherClass *myClass;

并确保在将类传递给手势识别器之前分配它,例如:

self.myClass = [[anotherClass alloc[init];
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:self.myClass action:@selector(bannerTapped:)];
//...
于 2014-02-13T15:26:48.913 回答
1

在以下行中:

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

您指定为目标的任何内容都是bannerTapped:将调用选择器的对象。所以你只需要anotherClass在那个参数中提供一个实例。大多数时候人们的目标是视图控制器,其中包含他们要添加识别器的视图,但这不是必需的。

于 2014-02-13T15:23:19.460 回答
-1

看起来您错过了名称末尾的“:”。@selector(bannerTapped:)

于 2019-11-13T05:52:36.813 回答