在UITapGesture Handler中访问UIImageView的标记值

时间:2012-09-18 03:10:59

标签: objective-c ios

我有一个附加到图像视图的UITapGesture。我想在几张图片中重复使用相同的手势。要做到这一点,处理程序方法需要能够识别点击来自哪个图像。以下方法尝试访问发件人图像视图的标记值。我基于这个问题https://stackoverflow.com/a/4425059/549273的答案。但是,我在调试器中收到一条错误,上面写着“发送到实例的无法识别的选择器”。我完全按照答案中的说法尝试了它,我也尝试将附加到方法的发送方作为参数,如下所示。 Netiher方法有效。有人能告诉我我做错了吗?

- (void)viewDidLoad
{
    [super viewDidLoad];

    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    topLeftImage.userInteractionEnabled = YES;
    [topLeftImage addGestureRecognizer:singleTap];

}

- (void)handleSingleTap:(UITapGestureRecognizer*)gestureView andSender:(id)sender {

    switch (((UIGestureRecognizer *)sender).view.tag)
    {
        case 0:
            NSLog(@"zero");
        case 1:
            NSLog(@"one");
    }

}

2 个答案:

答案 0 :(得分:0)

从UIGestureRecognizer类引用:

  

调用的操作方法必须符合以下之一   签名:

     
      
  • (无效)handleGesture;
  •   
  • (void)handleGesture:(UIGestureRecognizer *)gestureRecognizer;
  •   

您的方法(- (void)handleSingleTap:(UITapGestureRecognizer*)gestureView andSender:(id)sender)不符合任何一个签名。除此之外,当您创建手势识别器时,您正在使用与此功能不匹配的操作@selector(handleSingleTap:),因此甚至不应该调用它。试试这个:

- (void)viewDidLoad
{
    [super viewDidLoad];

    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    topLeftImage.userInteractionEnabled = YES;
    [topLeftImage addGestureRecognizer:singleTap];

}

- (void)handleSingleTap:(UIGestureRecognizer*)gestureView {

    switch (gestureView.view.tag)
    {
        case 0:
            NSLog(@"zero");
        case 1:
            NSLog(@"one");
    }

}

答案 1 :(得分:0)

同意@Inafziger(像往常一样),但这是一个更好的方法:在不同的视图上放置不同的手势识别器。

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
[topLeftImage addGestureRecognizer:singleTap];

// just like first as far as the target and selector, but a distinct object
singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
[bottomRightImage addGestureRecognizer:singleTap];

// and so on ...

现在,处理程序可以只询问gr所附加的视图。没有标签,没有开关声明。

- (void)handleSingleTap:(UIGestureRecognizer*)gr {
    UIImageView *theTappedView = (UIImageView *)gr.view
}