Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIView touch event in controller

How can I add UIView touchbegin action or touchend action programmatically as Xcode is not providing from Main.storyboard?

like image 240
dhaval shah Avatar asked May 28 '15 11:05

dhaval shah


People also ask

How does Uiview swift detect touch?

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.

How do I add tap gestures in Objective C?

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.

How do you make a Uiview clickable in Swift?

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..") }


2 Answers

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!") } 
like image 151
Miknash Avatar answered Nov 16 '22 00:11

Miknash


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 } 
like image 42
ventuz Avatar answered Nov 15 '22 23:11

ventuz