UIView touch event in controller

前端 未结 11 1801
梦毁少年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条回答
  •  Happy的楠姐
    2020-12-02 06:53

    Create outlets from views that were created in StoryBoard.

    @IBOutlet weak var redView: UIView!
    @IBOutlet weak var orangeView: UIView!
    @IBOutlet weak var greenView: UIView!   
    

    Override the touchesBegan method. There are 2 options, everyone can determine which one is better for him.

    1. Detect touch in special view.

      override func touchesBegan(_ touches: Set, with event: UIEvent?) {
           if let touch = touches.first {
              if touch.view == self.redView {
                  tapOnredViewTapped()
              } else if touch.view == self.orangeView {
                  orangeViewTapped()
              } else if touch.view == self.greenView {
                  greenViewTapped()
              } else {
                  return
              }
          }
      
      }
      
    2. Detect touch point on special view.

      override func touchesBegan(_ touches: Set, with event: UIEvent?) {
          if let touch = touches.first {
              let location = touch.location(in: view)
              if redView.frame.contains(location) {
                  redViewTapped()
              } else if orangeView.frame.contains(location) {
                  orangeViewTapped()
              } else if greenView.frame.contains(location) {
                  greenViewTapped()
              }
          }
      
      }
      

    Lastly, you need to declare the functions that will be called, depending on which view the user clicked.

    func redViewTapped() {
        print("redViewTapped")
    }
    
    func orangeViewTapped() {
        print("orangeViewTapped")
    }
    
    func greenViewTapped() {
        print("greenViewTapped")
    }
    

提交回复
热议问题