0

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

- (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");
    }

}
4

2 回答 2

0

从 UIGestureRecognizer 类参考:

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

  • (void)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");
    }

}
于 2012-09-18T03:22:37.260 回答
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 它附加到哪个视图。没有标签,没有 switch 语句。

- (void)handleSingleTap:(UIGestureRecognizer*)gr {
    UIImageView *theTappedView = (UIImageView *)gr.view
}
于 2012-09-18T03:28:01.607 回答