Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Touch Event on UIView

Does anyone have any sample code for detecting touches on a dynamically created UIView? I have found some references to touchesBegan but cannot figure out how to implement it...

like image 764
Andrew M Avatar asked Nov 09 '10 04:11

Andrew M


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 to add tap gesture recognizer to UIView?

Adding a Tap Gesture Recognizer in Interface Builder You don't need to switch between the code editor and Interface Builder. Open Main. storyboard and drag a tap gesture recognizer from the Object Library and drop it onto the 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..") }

How do I use UITapGestureRecognizer?

The iOS UITapGestureRecognizer class has a built-in way to detect a double tap on any view. All you need to do is create the recognizer, set its numberOfTapsRequired property to 2, then add it to the view you want to monitor.


1 Answers

A very general way to get touches is to override these methods in a custom UIView subclass:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event; - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event; - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event; - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event 

The official docs for these methods is under Responding to Touch Events in the UIResponder class docs (UIView inherits those methods since it's a subclass of UIResponder). Longer and more introductory docs can be found in the Event Handling Guide for iOS.

If you just want to detect a tap (touch-down, then touch-up within your view), it's easiest to add a UIButton as a subview of your view, and add your own custom method as a target/action pair for that button. Custom buttons are invisible by default, so it wouldn't affect the look of your view.

If you're looking for more advanced interactions, it's also good to know about the UIGestureRecognizer class.

like image 151
Tyler Avatar answered Oct 04 '22 18:10

Tyler