我只想为UIImageView
添加一个点击手势,当用户触摸时,调用另一个类(不是包含UIImageView
的同一个类)中实现的方法。
我可以这样做,如果可以,我该怎么做?
答案 0 :(得分:1)
你可以做到这一点。但是您需要 委托 或 委托 的 目标类的实例 (将在哪种方法中执行的类)在添加课程的手势中的东西。
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self.delegate action:@selector(doSomething)];
此处委托将是在转到该类之前必须设置的目标类的实例。
修改
我会再解释一下。假设您有两个视图控制器类VCA和VCB。你想通过点击手势从VCB调用VCA中的方法。
VCB.h中
@property (nonatomic,assign)VCA *delegate;
VCB.m中的
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self.delegate action:@selector(doSomething)];
VCA.m中的
您将呈现/推送VCB
VCB * viewController = [[VCB alloc]init];
viewController.delegate = self;
// push or present viewController
答案 1 :(得分:0)
在init
上声明识别器选择器UITapGestureRecognizer *recognizer =
[UITapGestureRecognizer
initWithTarget:objectOfAnotherClass
action:@selector(methodImplementedOnObjectOfAnotherClass:)];
答案 2 :(得分:0)
一种简单的方法是从tapGesture
的选择器方法调用另一个类的方法,即
将UITapGestureRecogniser添加到imageview
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapRecognised)];
[imageView addGestureRecognizer:tapGesture];
不要忘记启用UIImageView的userInteraction
,因为默认情况下,imageview userInteraction被禁用。
你可以像下面这样做。
imageView.userInteractionEnabled = YES;
然后在tapGestureRecogniser的选择器中调用另一个类的方法
- (void)tapRecognised
{
[next tappedOnImage];
}
这里next
是另一个类的对象。您也可以使用委托来调用该方法。
希望这会对你有所帮助。
答案 3 :(得分:0)
此处self.desired视图是您要添加手势的视图,您应该按照以下方式添加手势
和“webViewTapped.delegate = self”表示您想在用户点击时调用同一个类的函数,您可以使用委托像self.delegate将其更改为所需的函数
UITapGestureRecognizer *viewTapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
webViewTapped.numberOfTapsRequired = 1;
webViewTapped.delegate = self;
[self.desiredView addGestureRecognizer:viewTapped];
- (void)tapAction:(UITapGestureRecognizer *)sender;
{
// do your stuff here
}