How to call gesture tap on UIView programmatically in swift

后端 未结 23 1736
情歌与酒
情歌与酒 2020-11-28 18:50

I have a UIView and and I have added tap gesture to it:

let tap = UITapGestureRecognizer(target: self, action: Selector(\"handleTap:\"))
tap.delegate = self         


        
23条回答
  •  無奈伤痛
    2020-11-28 19:24

    try the following extension

        extension UIView {
    
        func  addTapGesture(action : @escaping ()->Void ){
            let tap = MyTapGestureRecognizer(target: self , action: #selector(self.handleTap(_:)))
            tap.action = action
            tap.numberOfTapsRequired = 1
    
            self.addGestureRecognizer(tap)
            self.isUserInteractionEnabled = true
    
        }
        @objc func handleTap(_ sender: MyTapGestureRecognizer) {
            sender.action!()
        }
    }
    
    class MyTapGestureRecognizer: UITapGestureRecognizer {
        var action : (()->Void)? = nil
    }
    

    and then use it :

    submitBtn.addTapGesture {
         //your code
    }
    

    you can even use it for cell

    cell.addTapGesture {
         //your code
    }
    

提交回复
热议问题