UIView touch event in controller
You will have to add it through code. Try this:
// 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!") }
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}
Swift 3:
let gesture = UITapGestureRecognizer(target: self, action: #selector(self.checkAction(sender:)))self.myView.addGestureRecognizer(gesture)func checkAction(sender : UITapGestureRecognizer) { // Do what you want}
Updating @Crashalot's answer for 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 }}