UIView touch event in controller

前端 未结 11 1823
梦毁少年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:47

    Just an update to above answers :

    If you want to have see changes in the click event, i.e. Color of your UIVIew shud change whenever user clicks the UIView then make changes as below...

    class ClickableUIView: UIView {
        override func touchesBegan(touches: Set, withEvent event: UIEvent?) {
                if let touch = touches.first {
                    let currentPoint = touch.locationInView(self)
                    // do something with your currentPoint
                }
    
                self.backgroundColor = UIColor.magentaColor()//Color when UIView is clicked.
            }
    
            override func touchesMoved(touches: Set, withEvent event: UIEvent?) {
                if let touch = touches.first {
                    let currentPoint = touch.locationInView(self)
                    // do something with your currentPoint
                }
    
                self.backgroundColor = UIColor.magentaColor()//Color when UIView is clicked.
            }
    
            override func touchesEnded(touches: Set, withEvent event: UIEvent?) {
                if let touch = touches.first {
                    let currentPoint = touch.locationInView(self)
                    // do something with your currentPoint
                }
    
                self.backgroundColor = UIColor.whiteColor()//Color when UIView is not clicked.
    
    }//class closes here
    

    Also, call this Class from Storyboard & ViewController as:

    @IBOutlet weak var panVerificationUIView:ClickableUIView!
    

提交回复
热议问题