13

我有一系列imageview安排,并为它分配一个TapView识别器

UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc]
                                         initWithTarget:self action:@selector(action:)];
[tapRecognizer setNumberOfTouchesRequired:1];
[tapRecognizer setDelegate:self];
imageView.userInteractionEnabled = YES;
[imageView addGestureRecognizer:tapRecognizer];

我将选择器定义为:

-(void) action:(id)sender
  {
    NSLog(@"TESTING TAP");
    NSLog (@"%d",[sender tag]);
  }

这正在崩溃,我收到错误消息:-

[UITapGestureRecognizer tag]: unrecognized selector sent to instance 0x145d0210

4

5 回答 5

38

你可以用这个..

UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc]
                                         initWithTarget:self action:@selector(action:)];
[tapRecognizer setNumberOfTouchesRequired:1];
[tapRecognizer setDelegate:self];
imageView.userInteractionEnabled = YES;
imageView.tag = 1111;
[imageView addGestureRecognizer:tapRecognizer];

并在行动中尝试这个..

-(void) action:(id)sender
  {
    NSLog(@"TESTING TAP");
    UITapGestureRecognizer *tapRecognizer = (UITapGestureRecognizer *)sender;
    NSLog (@"%d",[tapRecognizer.view tag]);
  }

解释:

UITapGestureRecognizer没有财产之类的tag。但它有属性view,从这个属性你可以访问UITapGestureRecognizer附加的视图。

希望对你有帮助

于 2013-10-03T07:09:13.967 回答
10

只需使用以下内容更改您的选择器方法..它会起作用

Tapgesture 将拥有被点击的整个视图..然后你可以从中获取标签属性,正如我在下面所说的那样

-(void)action:(UITapGestureRecognizer *)tapGesture{

     NSLog(@"TESTING TAP");
        NSLog (@"%d",tapGesture.view.tag);

    }
于 2013-10-03T07:31:38.970 回答
7

既不UITapGestureRecognizer也不UIGestureRecognizer声明名为 的属性或方法tag

你不能使用它。这就是您收到错误的原因。

在相关说明上。我真的不喜欢tag一般使用。总有一种更好的方法可以在不使用tag.

于 2013-10-03T06:52:10.150 回答
3

你不能得到它的tag属性,UITapGestureRecognizer而是你必须得到它的视图的属性,

你可以试试,

-(void)action:(id)sender
  {
     NSLog(@"TESTING TAP");
     NSLog (@"%d",[[sender view]tag]);

  }
于 2013-10-03T07:07:13.780 回答
3

Swift 等效于已接受的答案:

//use this to set up your tap gesture
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.reactToTap(sender:)))
imageView.tag = 33
imageView.isUserInteractionEnabled = true
imageView.addGestureRecognizer(tapGesture)

这是由水龙头触发的功能:

@objc private func reactToTap(sender: UITapGestureRecognizer) {
            
    print("ImageView tag: ", sender.view?.tag ?? 0) //"ImageView tag: 33"
}
于 2020-08-11T22:21:49.337 回答