iOS adding tapGesture to multiple Views

前端 未结 6 969
无人及你
无人及你 2020-12-31 03:11

I have multiple views defined in my main view. I want to add single tap gesture to all these views. Below is the code I have written, but this registers a tap gesture to the

6条回答
  •  被撕碎了的回忆
    2020-12-31 03:44

    to attach multiple views to same gesture you can reinitialize the gesture before affecting to your view

    here is an example in swift

    override func viewDidLoad() {
        super.viewDidLoad()
    
        var tap = UITapGestureRecognizer(target: self, action: #selector(infoTapped(sender:)))
        tap.numberOfTapsRequired = 1
        info1Btn.addGestureRecognizer(tap)
        info1Btn.tag = 1
    
        tap = UITapGestureRecognizer(target: self, action: #selector(infoTapped(sender:)))
        info2Btn.addGestureRecognizer(tap)
        info2Btn.tag = 2
    
        tap = UITapGestureRecognizer(target: self, action: #selector(infoTapped(sender:)))
        info3Btn.addGestureRecognizer(tap)
        info3Btn.tag = 3
    
    }
    
    
      @objc func infoTapped(sender: UITapGestureRecognizer){
        let view:UIView = sender.view!
        switch (view.tag) {
        case 1:
            print(view.tag) //  info 1 tapped
        case 2:
            print(view.tag) //  info2 tapped
    
        case 3:
            print(view.tag) //  info 3 tapped
    
        default:
            break;
        }
    }
    

提交回复
热议问题