How can I add UIView touchbegin action or touchend action programmatically as Xcode is not providing from Main.storyboard?
You can create touch gestures on an app's user interface solely through Swift code or by placing gesture recognizer objects on a view from the Object Library. To detect gestures in an app, you need to do the following: Add a gesture recognizer to a view. Create an IBAction method to respond to the gesture.
Adding a Tap Gesture Recognizer to an Image View in Interface Builder. Open Main. storyboard and drag a tap gesture recognizer from the Object Library and drop it onto the image view we added earlier. The tap gesture recognizer appears in the Document Outline on the left.
Swift 2.0 Version: // Add tap gesture recognizer to View let tapGesture = UITapGestureRecognizer(target: self, action: Selector("onClickOnView")) tapGesture. delegate = self self. view. addGestureRecognizer(tapGesture) func onClickOnView(){ print("You clicked on view..") }
You will have to add it through code. First, create the view and add it to the hierarchy:
var myView = UIView(frame: CGRectMake(100, 100, 100, 100)) self.view.addSubview(myView)
After that initialize gesture recognizer. Until Swift 2:
let gesture = UITapGestureRecognizer(target: self, action: "someAction:")
After Swift 2:
let gesture = UITapGestureRecognizer(target: self, action: #selector (self.someAction (_:)))
Then bind it to the view:
self.myView.addGestureRecognizer(gesture)
Swift 3:
func someAction(_ sender:UITapGestureRecognizer){ // do other task }
Swift 4 just add @objc
before func
:
@objc func someAction(_ sender:UITapGestureRecognizer){ // do other task }
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With