ios 点击手势识别器-点击了哪个对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21573036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 23:21:34  来源:igfitidea点击:

tap gesture recognizer - which object was tapped?

iosobjective-cuigesturerecognizeruitapgesturerecognizer

提问by suMi

I'm new to gesture recognizers so maybe this question sounds silly: I'm assigning tap gesture recognizers to a bunch of UIViews. In the method is it possible to find out which of them was tapped somehow or do I need to find it out using the point that was tapped on screen?

我是手势识别器的新手,所以这个问题可能听起来很傻:我正在将点击手势识别器分配给一堆 UIViews。在该方法中,是否可以找出其中哪些以某种方式被点击,或者我是否需要使用在屏幕上点击的点来找出它?

for (NSUInteger i=0; i<42; i++) {
        float xMultiplier=(i)%6;
        float yMultiplier= (i)/6;
        float xPos=xMultiplier*imageWidth;
        float yPos=1+UA_TOP_WHITE+UA_TOP_BAR_HEIGHT+yMultiplier*imageHeight;
        UIView *greyRect=[[UIView alloc]initWithFrame:CGRectMake(xPos, yPos, imageWidth, imageHeight)];
        [greyRect setBackgroundColor:UA_NAV_CTRL_COLOR];

        greyRect.layer.borderColor=[UA_NAV_BAR_COLOR CGColor];
        greyRect.layer.borderWidth=1.0f;
        greyRect.userInteractionEnabled=YES;
        [greyGridArray addObject:greyRect];
        [self.view addSubview:greyRect];
        NSLog(@"greyGrid: %i: %@", i, greyRect);

        //make them touchable
        UITapGestureRecognizer *letterTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(highlightLetter)];
        letterTapRecognizer.numberOfTapsRequired = 1;
        [greyRect addGestureRecognizer:letterTapRecognizer];
    }

回答by Mani

Define your target selector(highlightLetter:) with argument as

highlightLetter:用参数定义你的目标选择器( )

UITapGestureRecognizer *letterTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(highlightLetter:)];

Then you can get view by

然后你可以通过查看

- (void)highlightLetter:(UITapGestureRecognizer*)sender {
     UIView *view = sender.view; 
     NSLog(@"%d", view.tag);//By tag, you can find out where you had tapped. 
}

回答by Iftikhar Ali Ansari

Its been a year asking this question but still for someone.

问这个问题已经一年了,但仍然是为了某人。

While declaring the UITapGestureRecognizeron a particular view assign the tag as

UITapGestureRecognizer特定视图上声明时,将标记分配为

UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gestureHandlerMethod:)];
[yourGestureEnableView addGestureRecognizer:tapRecognizer];
yourGestureEnableView.tag=2;

and in your handler do like this

在你的处理程序中这样做

-(void)gestureHandlerMethod:(UITapGestureRecognizer*)sender {
    if(sender.view.tag == 2) {
        // do something here
    }
}

回答by tech4242

Here is an update for Swift 3and an addition to Mani's answer. I would suggest using sender.viewin combination with tagging UIViews (or other elements, depending on what you are trying to track) for a somewhat more "advanced" approach.

这是Swift 3的更新和 Mani 答案的补充。我建议sender.view结合使用标记 UIViews(或其他元素,取决于您要跟踪的内容)以获得更“高级”的方法。

  1. Adding the UITapGestureRecognizer to e.g. an UIButton (you can add this to UIViews etc. as well) Or a whole bunch of items in an array with a for-loop and a second array for the tap gestures.
  1. 将 UITapGestureRecognizer 添加到例如 UIButton(您也可以将其添加到 UIViews 等)或数组中的一大堆项目,其中包含一个 for 循环和一个用于点击手势的第二个数组。
    let yourTapEvent = UITapGestureRecognizer(target: self, action: #selector(yourController.yourFunction)) 
    yourObject.addGestureRecognizer(yourTapEvent) // adding the gesture to your object
  1. Defining the function in the same testController (that's the name of your View Controller). We are going to use tagshere - tags are Int IDs, which you can add to your UIView with yourButton.tag = 1. If you have a dynamic list of elements like an array you can make a for-loop, which iterates through your array and adds a tag, which increases incrementally

    func yourFunction(_ sender: AnyObject) {
        let yourTag = sender.view!.tag // this is the tag of your gesture's object
        // do whatever you want from here :) e.g. if you have an array of buttons instead of just 1:
        for button in buttonsArray {
          if(button.tag == yourTag) {
            // do something with your button
          }
        }
    }
    
  1. 在同一个 testController 中定义函数(这是您的视图控制器的名称)。我们将在这里使用标签- 标签是 Int ID,您可以使用yourButton.tag = 1. 如果你有一个像数组这样的动态元素列表,你可以做一个 for 循环,它遍历你的数组并添加一个标签,这个标签会逐渐增加

    func yourFunction(_ sender: AnyObject) {
        let yourTag = sender.view!.tag // this is the tag of your gesture's object
        // do whatever you want from here :) e.g. if you have an array of buttons instead of just 1:
        for button in buttonsArray {
          if(button.tag == yourTag) {
            // do something with your button
          }
        }
    }
    

The reason for all of this is because you cannot pass further arguments for yourFunction when using it in conjunction with #selector.

所有这一切的原因是因为当与 #selector 结合使用时,您无法为 yourFunction 传递更多参数。

If you have an even more complex UI structure and you want to get the parent's tag of the item attached to your tap gesture you can use let yourAdvancedTag = sender.view!.superview?.tage.g. getting the UIView's tag of a pressed button inside that UIView; can be useful for thumbnail+button lists etc.

如果你有一个更复杂的 UI 结构,并且你想要获得附加到你的点击手势的项目的父标签,你可以使用let yourAdvancedTag = sender.view!.superview?.tag例如获取 UIView 中按下按钮的 UIView 标签;可用于缩略图+按钮列表等。

回答by Dilip Tilonia

in swift it quite simple

很快就很简单

Write this code in ViewDidLoad() function

在 ViewDidLoad() 函数中编写此代码

let tap = UITapGestureRecognizer(target: self, action: #selector(tapHandler(gesture:)))
    tap.numberOfTapsRequired = 2
    tapView.addGestureRecognizer(tap)

The Handler Part this could be in viewDidLoad or outside the viewDidLoad, batter is put in extension

Handler 部分这可以在viewDidLoad 或viewDidLoad 之外,batter 放在扩展中

@objc func tapHandler(gesture: UITapGestureRecognizer) {
    currentGestureStates.text = "Double Tap"
} 

here i'm just testing the code by printing the output if you want to make an action you can do whatever you want or more practise and read

在这里,我只是通过打印输出来测试代码,如果你想做一个动作,你可以做任何你想做的事情或者更多的练习和阅读

回答by Phani Sai

Use this code in Swift

在 Swift 中使用此代码

func tappGeastureAction(sender: AnyObject) {
    if let tap = sender as? UITapGestureRecognizer {
        let point = tap.locationInView(locatedView)
        if filterView.pointInside(point, withEvent: nil) == true {
            // write your stuff here                
        }
    }
}

回答by Bonnie

you can use

您可以使用

 - (void)highlightLetter:(UITapGestureRecognizer*)sender {
     UIView *view = sender.view; 
     NSLog(@"%d", view.tag); 
}

view will be the Object in which the tap gesture was recognised

视图将是识别点击手势的对象

回答by Fawad Masud

You can also use "shouldReceiveTouch" method of UIGestureRecognizer

您还可以使用 UIGestureRecognizer 的“shouldReceiveTouch”方法

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:     (UITouch *)touch {
     UIView *view = touch.view; 
     NSLog(@"%d", view.tag); 
}    

Dont forget to set delegate of your gesture recognizer.

不要忘记设置手势识别器的委托。

回答by Fattie

Typical 2019 example

2019年典型例子

Say you have a FaceViewwhich is some sort of image. You're going to have manyof them on screen (or, in a collection view, table, stack view or other list).

假设你有一个FaceView这是某种图像。你将有很多人在屏幕上(或者,在收集视图,表,堆栈视图或其他列表)。

In the class FaceViewyou will need a variable "index"

在课堂上,FaceView您将需要一个变量“索引”

class FaceView: UIView {
   var index: Int

so that each FaceView can be self-aware of "which" face it is on screen.

这样每个 FaceView 都可以自我意识到它在屏幕上的“哪个”面孔。

So you must add var index: Intto the class in question.

所以你必须添加var index: Int到有问题的类中。

So you are adding many FaceView to your screen ...

所以你在你的屏幕上添加了许多 FaceView ......

let f = FaceView()
f.index = 73
.. you add f to your stack view, screen, or whatever.

You now add a click to f

你现在添加一个点击 f

f.addGestureRecognizer(UITapGestureRecognizer(target: self,
                           action: #selector(tapOneOfTheFaces)))

Here's the secret:

这是秘密:

@objc func tapOneOfTheFaces(_ sender: UITapGestureRecognizer) {
    if let tapped = sender.view as? CirclePerson {
        print("we got it: \(tapped.index)")

You now know "which" face was clicked in your table, screen, stack view or whatever.

您现在知道在您的表格、屏幕、堆栈视图或其他任何内容中单击了“哪个”面。

It's that easy.

就这么简单。

回答by Greg

You should amend creation of the gesture recogniser to accept parameter (add colon ':')

您应该修改手势识别器的创建以接受参数(添加冒号':')

UITapGestureRecognizer *letterTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(highlightLetter:)];

And in your method highlightLetter: you can access the view attached to recogniser:

在您的方法 highlightLetter: 中,您可以访问附加到识别器的视图:

-(IBAction) highlightLetter:(UITapGestureRecognizer*)recognizer
{
    UIView *view = [recognizer view];
}

回答by Manjeet

func tabGesture_Call
{
     let tapRec = UITapGestureRecognizer(target: self, action: "handleTap:")
     tapRec.delegate = self
     self.view.addGestureRecognizer(tapRec)
     //where we want to gesture like: view, label etc
}

func handleTap(sender: UITapGestureRecognizer) 
{
     NSLog("Touch..");
     //handling code
}