tap gesture recognizer - which object was tapped?

前端 未结 12 1336
萌比男神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:17

    Typical 2019 example

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

    In the class FaceView you will need a variable "index"

    class FaceView: UIView {
       var index: Int
    

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

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

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

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

    You now add a click to 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.

提交回复
热议问题