UIView touch event in controller

前端 未结 11 1827
梦毁少年i
梦毁少年i 2020-12-02 06:26

How can I add UIView touchbegin action or touchend action programmatically as Xcode is not providing from Main.storyboard?

11条回答
  •  没有蜡笔的小新
    2020-12-02 06:46

    you can used this way: create 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 use this way:

    @IBOutlet weak var testView: UIView!
    testView.addTapGesture{
       // ...
    }
    

提交回复
热议问题