【问题标题】:UIView touch event in controller控制器中的 UIView 触摸事件
【发布时间】:2015-08-10 21:05:49
【问题描述】:

由于 Xcode 未从 Main.storyboard 提供,我如何以编程方式添加 UIView touchbegin 操作或 touchend 操作?

【问题讨论】:

  • 那个是按钮,OP想为UIView添加事件
  • 使用UILongPressGestureRecognizer 并将minimumPressDuration 设置为零。 See this answer. 它不需要继承或覆盖任何东西。

标签: ios swift uiview uiviewcontroller


【解决方案1】:

您必须通过代码添加它。试试这个:

    // 1.create UIView programmetically
    var myView = UIView(frame: CGRectMake(100, 100, 100, 100))
    // 2.add myView to UIView hierarchy
    self.view.addSubview(myView) 
    // 3. add action to myView
    let gesture = UITapGestureRecognizer(target: self, action: "someAction:")
    // or for swift 2 +
    let gestureSwift2AndHigher = UITapGestureRecognizer(target: self, action:  #selector (self.someAction (_:)))
    self.myView.addGestureRecognizer(gesture)

    func someAction(sender:UITapGestureRecognizer){     
       // do other task
    }

    // or for Swift 3
    func someAction(_ sender:UITapGestureRecognizer){     
       // do other task
    }

    // or for Swift 4
    @objc func someAction(_ sender:UITapGestureRecognizer){     
       // do other task
    }

    // update for Swift UI

    Text("Tap me!")
        .tapAction {
             print("Tapped!")
        }

【讨论】:

  • 我已经做到了,当我点击 uiView 时它给了我一个错误。我的代码: let gesture = UITapGestureRecognizer(target: self.uiPendingView, action: "touchPending") self.uiPendingView.addGestureRecognizer(gesture) 和方法: func touchPending(sender: AnyObject) { println("METHOD>>>>>>> >>>>>>>>>>") }
  • 只需在 "touchPending:" ans 函数中添加:它看起来像 func touchPending(sender: UITapGestureRecognizer)
  • 你在行动中缺少':'。
  • 您好,当 UIView 都具有相同的 someAction 函数时,如何区分点击了哪个 UIView?
  • 最简单的方法是使用标签属性,然后在函数中确定哪个视图是发件人
【解决方案2】:

Swift 4 / 5:

let gesture = UITapGestureRecognizer(target: self, action:  #selector(self.checkAction))
self.myView.addGestureRecognizer(gesture)

@objc func checkAction(sender : UITapGestureRecognizer) {
    // Do what you want
}

斯威夫特 3:

let gesture = UITapGestureRecognizer(target: self, action:  #selector(self.checkAction(sender:)))
self.myView.addGestureRecognizer(gesture)

func checkAction(sender : UITapGestureRecognizer) {
    // Do what you want
}

【讨论】:

  • 应从 VIEWDIDLOAD 调用前 2 行!
【解决方案3】:

更新@Crashalot 对 Swift 3.x 的回答:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.location(in: self)
        // do something with your currentPoint
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.location(in: self)
        // do something with your currentPoint
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.location(in: self)
        // do something with your currentPoint
    }
}

【讨论】:

    【解决方案4】:

    更新@Chackle 对 Swift 2.x 的回答:

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        if let touch = touches.first {
            let currentPoint = touch.locationInView(self)
            // do something with your currentPoint
        }
    }
    
    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
        if let touch = touches.first {
            let currentPoint = touch.locationInView(self)
            // do something with your currentPoint
        }
    }
    
    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
        if let touch = touches.first {
            let currentPoint = touch.locationInView(self)
            // do something with your currentPoint
        }
    }
    

    【讨论】:

      【解决方案5】:

      把它放在你的UIView 子类中(如果你为此功能创建一个子类是最简单的)。

      class YourView: UIView {
      
        //Define your initialisers here
      
        override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
          if let touch = touches.first as? UITouch {
            let currentPoint = touch.locationInView(self)
            // do something with your currentPoint
          }
        }
      
        override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
          if let touch = touches.first as? UITouch {
            let currentPoint = touch.locationInView(self)
            // do something with your currentPoint
          }
        }
      
        override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
          if let touch = touches.first as? UITouch {
            let currentPoint = touch.locationInView(self)
            // do something with your currentPoint
          }
        }
      }
      

      【讨论】:

      • @Chacle,我的页面中有超过 10 个 Uiview,我想在一些 Sub UIView 中添加操作。那么为此我应该改变什么?
      • 这取决于你想用它做什么。您想知道您按的是哪个UIView,还是要在每个UIView 中处理一些压力?
      • 我只想要一些特定 UIview 的 touchevent。
      【解决方案6】:

      对于 Swift 4

      @IBOutlet weak var someView: UIView!  
      let gesture = UITapGestureRecognizer(target: self, action:  #selector (self.someAction (_:)))
      self.someView.addGestureRecognizer(gesture)
      
      @objc func someAction(_ sender:UITapGestureRecognizer){
          print("view was clicked")
      }
      

      【讨论】:

        【解决方案7】:

        从 StoryBoard 中创建的视图创建出口。

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

        重写 touchesBegan 方法。有两种选择,大家可以自行判断哪一种更适合自己。

        1. 在特殊视图中检测触摸。

          override func touchesBegan(_ touches: Set<UITouch>, 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. 在特殊视图上检测触摸点。

          override func touchesBegan(_ touches: Set<UITouch>, 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()
                  }
              }
          
          }
          

        最后,您需要声明将调用的函数,具体取决于用户单击的视图。

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

        【讨论】:

        • 非常好的例子,感谢向我展示!我们也可以使用 touchEvent 来做到这一点。我只知道按钮和手势两种方式。谢谢+1
        • 顺便说一下,这种触摸在模拟器中不起作用。所以如果你在模拟器上工作,你不能测试代码。
        【解决方案8】:

        你可以这样使用: 创建扩展

        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
        }
        

        并以这种方式使用:

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

        【讨论】:

          【解决方案9】:

          斯威夫特 4.2:

          @IBOutlet weak var viewLabel1: UIView!
          @IBOutlet weak var viewLabel2: UIView!
            override func viewDidLoad() {
              super.viewDidLoad()
          
              let myView = UITapGestureRecognizer(target: self, action: #selector(someAction(_:)))
              self.viewLabel1.addGestureRecognizer(myView)
          }
          
           @objc func someAction(_ sender:UITapGestureRecognizer){
             viewLabel2.isHidden = true
           }
          

          【讨论】:

            【解决方案10】:

            只是对上述答案的更新:

            如果您想看到点击事件的变化,即当用户点击 UIView 时 UIVIew 的颜色会发生变化,然后进行如下更改...

            class ClickableUIView: UIView {
                override func touchesBegan(touches: Set<UITouch>, 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<UITouch>, 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<UITouch>, 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
            

            另外,从 Storyboard 和 ViewController 中调用这个类:

            @IBOutlet weak var panVerificationUIView:ClickableUIView!
            

            【讨论】:

              【解决方案11】:

              更新@stevo.mit 对 Swift 4.x 的回答:

              override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
                  if let touch = touches.first {
                      let currentPoint = touch.location(in: self.view)
                      // do something with your currentPoint
                  }
              }
              
              override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
                  if let touch = touches.first {
                      let currentPoint = touch.location(in: self.view)
                      // do something with your currentPoint
                  }
              }
              
              override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
                  if let touch = touches.first {
                      let currentPoint = touch.location(in: self.view)
                      // do something with your currentPoint
                  }
              }
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2011-05-07
                • 2010-12-02
                • 2013-07-22
                • 2021-02-09
                • 2011-08-12
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多