tap gesture recognizer - which object was tapped?

前端 未结 12 1316
萌比男神i
萌比男神i 2020-12-29 17:47

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 w

12条回答
  •  灰色年华
    2020-12-29 18:31

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

    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.
        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 tags here - 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
            }
          }
      }
      

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

    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?.tag e.g. getting the UIView's tag of a pressed button inside that UIView; can be useful for thumbnail+button lists etc.

提交回复
热议问题