Double touch on UIButton - ios

How to recognize double touch on UIButton ?

Add an target-action for the control event UIControlEventTouchDownRepeat, and do action only when the touch's tapCount is 2.
Objective-C:
[button addTarget:self action:#selector(multipleTap:withEvent:)
forControlEvents:UIControlEventTouchDownRepeat];
...
-(IBAction)multipleTap:(id)sender withEvent:(UIEvent*)event {
UITouch* touch = [[event allTouches] anyObject];
if (touch.tapCount == 2) {
// do action.
}
}
As #Gavin commented, double-tap on a button is an unusual gesture. On the iPhone OS double-tap is mostly used for zoomable views to zoom into/out of a region of focus. It may be unintuitive for the users if you make the gesture to perform other actions.
Swift 3:
button.addTarget(self, action: #selector(multipleTap(_:event:)), for: UIControlEvents.touchDownRepeat)
And then:
func multipleTap(_ sender: UIButton, event: UIEvent) {
let touch: UITouch = event.allTouches!.first!
if (touch.tapCount == 2) {
// do action.
}
}

If you are working with swift 5, #kennytm's solution won't work. So you can write an objective-c/swift function and add it as gesture with number of desired taps.
let tap = UITapGestureRecognizer(target: self, action: #selector(doubleTapped))
tap.numberOfTapsRequired = 2
btn.addGestureRecognizer(tap)
and then
#objc func doubleTapped() {
// your desired behaviour.
}
Here button can be tapped any number of times and it will show as tapped. But the above function won't execute until button tapped for required number of times.

[button addTarget:self action:#selector(button_TouchDown:) forControlEvents:UIControlEventTouchDown];
[button addTarget:self action:#selector(button_TouchDownRepeat:withEvent:) forControlEvents:UIControlEventTouchDownRepeat];
-(void)button_one_tap:(UIButton*) button
{
NSLog(#"button_one_tap");
}
-(void)button_double_tap:(UIButton*) button
{
NSLog(#"button_double_tap");
}
-(void)button_TouchDown:(UIButton*) button
{
NSLog(#"button_TouchDown");
[self performSelector:#selector(button_one_tap:) withObject:button afterDelay:0.3 /*NSEvent.doubleClickInterval maybe too long*/];
}
-(void)button_TouchDownRepeat:(UIButton*) button withEvent:(UIEvent*)event {
NSLog(#"button_TouchDownRepeat");
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:#selector(button_one_tap:) object:button];
UITouch* touch = [[event allTouches] anyObject];
//NSLog(#"touch.tapCount = %ld", touch.tapCount);
if (touch.tapCount == 2) {
// do action.
[self button_double_tap:button];
}
}

#IBOutlet weak var button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
button.addTarget(self, action: "didTap:", forControlEvents: .TouchUpInside)
button.addTarget(self, action: "didDoubleTap:", forControlEvents: .TouchDownRepeat)
}
var ignoreTap = false
func didTap(sender: UIButton) {
if ignoreTap {
ignoreTap = false
print("ignoretap", sender)
return
}
print("didTap", sender)
}
func didDoubleTap(sender: UIButton) {
ignoreTap = true
print("didDoubleTap", sender)
}

try to use this for the button event
UIControlEventTouchDownRepeat

Related

UIBarButtonItem Long Press / Short Press

I have looked through the existing questions on this subject matter, and there appears to be no answers post iOS 11 (which appeared to break the gesturerecognizers).
Is there a way to detect the short press / long press on a UIBarButtonItem? Apple uses this functionality in Pages, Numbers, Keynote for Undo / Redo.
Just replace your default event handler for the tap event
-(void)handlerForBarButton:(UIBarButtonItem*)p_Sender
with its extend version
-(void)handlerForBarButton:(UIBarButtonItem*)p_Sender forEvent:(UIEvent*)p_Event
By inspecting the UIEvent object you can learn, if the event was a long press (tapCount of first UITouch object is 0).
This is my code for a playback rate button that returns the rate to '1x' if the bar button item is pressed longer the about one second:
/*
rateButtonPressed:forEvent:
*/
- (IBAction)rateButtonPressed:(UIBarButtonItem*)p_Sender
forEvent:(UIEvent*)p_Event
{
UITouch* firstTouch = nil;
if ( (nil != ((firstTouch = p_Event.allTouches.allObjects.firstObject)))
&& (0 == firstTouch.tapCount))
{
self.avAudioPlayer.rate = 1.0;
}
else
{ // Default tap
if (2.0 == self.avAudioPlayer.rate)
{
self.avAudioPlayer.rate = 0.5;
}
else
{
self.avAudioPlayer.rate += 0.25;
}
}
[WBSettingsSharedInstance.standardUserDefaults setDouble:self.avAudioPlayer.rate
forKey:#"audioPlayerRate"];
[self updateRateBarButton];
}
Try this
#IBOutlet weak var btn: UIButton!
override func viewDidLoad() {
let tapGesture = UITapGestureRecognizer(target: self, #selector (tap)) //Tap function will call when user tap on button
let longGesture = UILongPressGestureRecognizer(target: self, #selector(long)) //Long function will call when user long press on button.
tapGesture.numberOfTapsRequired = 1
btn.addGestureRecognizer(tapGesture)
btn.addGestureRecognizer(longGesture)
}
#objc func tap() {
print("Single tap done")
}
#objc func long() {
print("Long gesture recognized")
}

How to click a button lying below UITableView

say, I have a button lying under UITableView, how can I click the button through the UITableViewCell but do not trigger the cell click event:
The reason I put the button behind the tableview is that I want to see and click the button under the cell whose color set to be clear, and when I scroll the table, the button can be covered by cell which is not with clear color
I created a sample project and got it working:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let tap = UITapGestureRecognizer(target: self, action: #selector(TableViewVC.handleTap))
tap.numberOfTapsRequired = 1
self.view.addGestureRecognizer(tap)
}
func handleTap(touch: UITapGestureRecognizer) {
let touchPoint = touch.locationInView(self.view)
let isPointInFrame = CGRectContainsPoint(button.frame, touchPoint)
print(isPointInFrame)
if isPointInFrame == true {
print("button pressed")
}
}
To check of button is really being pressed we need to use long tap gesture:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let tap = UILongPressGestureRecognizer(target: self, action: #selector(TableViewVC.handleTap))
tap.minimumPressDuration = 0.01
self.view.addGestureRecognizer(tap)
}
func handleTap(touch: UILongPressGestureRecognizer) {
let touchPoint = touch.locationInView(self.view)
print(" pressed")
if touch.state == .Began {
let isPointInFrame = CGRectContainsPoint(button.frame, touchPoint)
print(isPointInFrame)
if isPointInFrame == true {
print("button pressed")
button.backgroundColor = UIColor.lightGrayColor()
}
}else if touch.state == .Ended {
button.backgroundColor = UIColor.whiteColor()
}
}
Get the touch point on the main view. Then use following method to check the touch point lies inside the button frame or not.
bool CGRectContainsPoint(CGRect rect, CGPoint point)
You can write your custom view to touch button or special view behind the topview
class MyView: UIView {
override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
for subview in self.subviews {
if subview is UIButton {
let subviewPoint = self.convertPoint(point, toView: subview)
if subview.hitTest(subviewPoint, withEvent: event) != nil { // if touch inside button view, return button to handle event
return subview
}
}
}
// if not inside button return nomal action
return super.hitTest(point, withEvent: event)
}
}
Then set your controller view to custom MyView class

Is there something that will repeat touchesBegan?

I have a button that when getting pressed will move a node. How can I repeat this non stop while button is pressed. I guess I'm looking for something between touchesBegan and touchesEnded. Something like touchesContinue because I'd like the node to continue moving while the button is pressed. This is what I have so far.
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
// 1
leftMove.name = "Left"
rightMove.name = "Right"
/* Called when a touch begins */
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
let node = self.nodeAtPoint(location)
if (node.name == "Left") {
// Implement your logic for left button touch here:
player.position == CGPoint(x:player.position.x-1, y:player.position.y)
} else if (node.name == "Right") {
// Implement your logic for right button touch here:
player.position = CGPoint(x:player.position.x+1, y:player.position.y)
}
}
Use NSTimer to repeat the move action. Have the timer started on the Touch Down and have the timer stopped on either Touch Up Inside or Touch Up Outside.
import UIKit
class ViewController: UIViewController, UIScrollViewDelegate {
var button: UIButton!
var timer: NSTimer!
leftMove.name = "Left"
rightMove.name = "Right"
override func viewDidLoad() {
super.viewDidLoad()
button = UIButton(frame: CGRectMake(100, 100, 50, 50)) as UIButton
//add Target for .TouchDown events, when user touch down
button.addTarget(self, action: #selector(ViewController.touchDown(_:)), forControlEvents: .TouchDown)
//add Target for .TouchUpInside events, when user release the touch
button.addTarget(self, action: #selector(ViewController.release(_:)), forControlEvents: .TouchUpInside)
view.addSubview(button)
}
func touchDown(sender: UIButton) {
//start the timer
timer = NSTimer.scheduledTimerWithTimeInterval(0.3, target: self, selector: #selector(ViewController.movePlayer(_:)), userInfo: nil, repeats: true)
}
func release(sender: UIButton) {
//stop the timer
self.timer.invalidate()
self.timer = nil
}
func movePlayer(sender: NSTimer) {
//move your stuff here
let location = touch.locationInNode(self)
let node = self.nodeAtPoint(location)
if (node.name == "Left") {
// Implement your logic for left button touch here:
player.position == CGPoint(x:player.position.x-1, y:player.position.y)
} else if (node.name == "Right") {
// Implement your logic for right button touch here:
player.position = CGPoint(x:player.position.x+1, y:player.position.y)
}
}
}
THIS IS IN OBJECTIVE C
i suggest you to use this i did it with touch down event
create Timer object global
TOUCH UP INSIDE and Drag and EXIT
- (IBAction)arrowUpUpperLipTapped:(UIButton *)sender {
NSLog(#"SIngle TAPPED");
if (self.timer1) {
[self.timer1 invalidate];
self.timer1 = nil;
}
[self arrowUpperLipPosChanged:sender];
}
//-----------------------------------------------------------------------
TOUCH DOWN
- (IBAction)arrowUpperLipLongTapped:(UIButton *)sender {
NSLog(#"LONG TAPPED");
if (self.timer) {
[self.timer1 invalidate];
self.timer1 = nil;
}
_timer1 = [NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:#selector(arrowUpperLipTimerAction:) userInfo:sender repeats:YES];
}
//-----------------------------------------------------------------------
- (void) arrowUpperLipPosChanged :(UIButton *) sender {
CGRect frame = self.viewUpperLip.frame;
if (sender.tag == 9001) {
// UP Arrow Tapped
frame.origin.y --;
} else if (sender.tag == 9002) {
frame.origin.y ++;
}
if (!CGRectContainsPoint(CGRectMake(frame.origin.x, frame.origin.y + frame.size.height / 2, frame.size.width, frame.size.height), self.imgViewGridHEyesCenter.center) && !(CGRectIntersection(frame, [self.view viewWithTag:203].frame).size.height >= frame.size.height)) {
[self.viewUpperLip setFrame:frame];
}
}
//-----------------------------------------------------------------------
- (void) arrowUpperLipTimerAction :(NSTimer *) timer {
UIButton *sender = (UIButton *)[timer userInfo];
[self arrowUpperLipPosChanged:sender];
}

How to detect touch end event for UIButton?

I want to handle an event occurs when UIButton touch is ended. I know that UIControl has some events implementing touches (UIControlEventTouchDown, UIControlEventTouchCancel, etc.). But I can't catch any of them except UIControlEventTouchDown and UIControlEventTouchUpInside.
My button is a subview of some UIView. That UIView has userInteractionEnabled property set to YES.
What's wrong?
You can set 'action targets' for your button according to the ControlEvents
- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;
Example:
[yourButton addTarget:self
action:#selector(methodTouchDown:)
forControlEvents:UIControlEventTouchDown];
[yourButton addTarget:self
action:#selector(methodTouchUpInside:)
forControlEvents: UIControlEventTouchUpInside];
-(void)methodTouchDown:(id)sender{
NSLog(#"TouchDown");
}
-(void)methodTouchUpInside:(id)sender{
NSLog(#"TouchUpInside");
}
You need to create your own custom class that extends UIButton.
your header file should look like this.
#interface customButton : UIButton
{
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
then make your implementation file
#Ramshad's accepted answer in Swift 3.0 syntax
using following method of UIControl class
open func addTarget(_ target: Any?, action: Selector, for controlEvents: UIControlEvents)
Example:
myButton.addTarget(self, action: #selector(MyViewController.touchDownEvent), for: .touchDown)
myButton.addTarget(self, action: #selector(MyViewController.touchUpEvent), for: [.touchUpInside, .touchUpOutside])
func touchDownEvent(_ sender: AnyObject) {
print("TouchDown")
}
func touchUpEvent(_ sender: AnyObject) {
print("TouchUp")
}
Swift 3.0 version:
let btn = UIButton(...)
btn.addTarget(self, action: #selector(MyView.onTap(_:)), for: .touchUpInside)
func onTap(_ sender: AnyObject) -> Void {
}
i think it is more easy
UILongPressGestureRecognizer *longPressOnButton = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:#selector(longPressOnButton:)];
longPressOnButton.delegate = self;
btn.userInteractionEnabled = YES;
[btn addGestureRecognizer:longPressOnButton];
- (void)longPressOnButton:(UILongPressGestureRecognizer*)gesture
{
// When you start touch the button
if (gesture.state == UIGestureRecognizerStateBegan)
{
//start recording
}
// When you stop touch the button
if (gesture.state == UIGestureRecognizerStateEnded)
{
//end recording
}
}
Just add IBOutlets for UIButton with Events TouchDown: and Primary Action Triggered:
- (IBAction)touchDown:(id)sender {
NSLog(#"This will trigger when button is Touched");
}
- (IBAction)primaryActionTriggered:(id)sender {
NSLog(#"This will trigger Only when touch end within Button Boundary (not Frame)");
}

How to add a touch event to a UIView?

How do I add a touch event to a UIView?
I try:
UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, nextY)] autorelease];
[headerView addTarget:self action:#selector(myEvent:) forControlEvents:UIControlEventTouchDown];
// ERROR MESSAGE: UIView may not respond to '-addTarget:action:forControlEvents:'
I don't want to create a subclass and overwrite
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
In iOS 3.2 and higher, you can use gesture recognizers. For example, this is how you would handle a tap event:
//The setup code (in viewDidLoad in your view controller)
UITapGestureRecognizer *singleFingerTap =
[[UITapGestureRecognizer alloc] initWithTarget:self
action:#selector(handleSingleTap:)];
[self.view addGestureRecognizer:singleFingerTap];
//The event handling method
- (void)handleSingleTap:(UITapGestureRecognizer *)recognizer
{
CGPoint location = [recognizer locationInView:[recognizer.view superview]];
//Do stuff here...
}
There are a bunch of built in gestures as well. Check out the docs for iOS event handling and UIGestureRecognizer. I also have a bunch of sample code up on github that might help.
Gesture Recognizers
There are a number of commonly used touch events (or gestures) that you can be notified of when you add a Gesture Recognizer to your view. They following gesture types are supported by default:
UITapGestureRecognizer Tap (touching the screen briefly one or more times)
UILongPressGestureRecognizer Long touch (touching the screen for a long time)
UIPanGestureRecognizer Pan (moving your finger across the screen)
UISwipeGestureRecognizer Swipe (moving finger quickly)
UIPinchGestureRecognizer Pinch (moving two fingers together or apart - usually to zoom)
UIRotationGestureRecognizer Rotate (moving two fingers in a circular direction)
In addition to these, you can also make your own custom gesture recognizer.
Adding a Gesture in the Interface Builder
Drag a gesture recognizer from the object library onto your view.
Control drag from the gesture in the Document Outline to your View Controller code in order to make an Outlet and an Action.
This should be set by default, but also make sure that User Action Enabled is set to true for your view.
Adding a Gesture Programmatically
To add a gesture programmatically, you (1) create a gesture recognizer, (2) add it to a view, and (3) make a method that is called when the gesture is recognized.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var myView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// 1. create a gesture recognizer (tap gesture)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(sender:)))
// 2. add the gesture recognizer to a view
myView.addGestureRecognizer(tapGesture)
}
// 3. this method is called when a tap is recognized
#objc func handleTap(sender: UITapGestureRecognizer) {
print("tap")
}
}
Notes
The sender parameter is optional. If you don't need a reference to the gesture then you can leave it out. If you do so, though, remove the (sender:) after the action method name.
The naming of the handleTap method was arbitrary. Name it whatever you want using action: #selector(someMethodName(sender:)).
More Examples
You can study the gesture recognizers that I added to these views to see how they work.
Here is the code for that project:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var tapView: UIView!
#IBOutlet weak var doubleTapView: UIView!
#IBOutlet weak var longPressView: UIView!
#IBOutlet weak var panView: UIView!
#IBOutlet weak var swipeView: UIView!
#IBOutlet weak var pinchView: UIView!
#IBOutlet weak var rotateView: UIView!
#IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Tap
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap))
tapView.addGestureRecognizer(tapGesture)
// Double Tap
let doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap))
doubleTapGesture.numberOfTapsRequired = 2
doubleTapView.addGestureRecognizer(doubleTapGesture)
// Long Press
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(gesture:)))
longPressView.addGestureRecognizer(longPressGesture)
// Pan
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan(gesture:)))
panView.addGestureRecognizer(panGesture)
// Swipe (right and left)
let swipeRightGesture = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(gesture:)))
let swipeLeftGesture = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(gesture:)))
swipeRightGesture.direction = UISwipeGestureRecognizerDirection.right
swipeLeftGesture.direction = UISwipeGestureRecognizerDirection.left
swipeView.addGestureRecognizer(swipeRightGesture)
swipeView.addGestureRecognizer(swipeLeftGesture)
// Pinch
let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(handlePinch(gesture:)))
pinchView.addGestureRecognizer(pinchGesture)
// Rotate
let rotateGesture = UIRotationGestureRecognizer(target: self, action: #selector(handleRotate(gesture:)))
rotateView.addGestureRecognizer(rotateGesture)
}
// Tap action
#objc func handleTap() {
label.text = "Tap recognized"
// example task: change background color
if tapView.backgroundColor == UIColor.blue {
tapView.backgroundColor = UIColor.red
} else {
tapView.backgroundColor = UIColor.blue
}
}
// Double tap action
#objc func handleDoubleTap() {
label.text = "Double tap recognized"
// example task: change background color
if doubleTapView.backgroundColor == UIColor.yellow {
doubleTapView.backgroundColor = UIColor.green
} else {
doubleTapView.backgroundColor = UIColor.yellow
}
}
// Long press action
#objc func handleLongPress(gesture: UILongPressGestureRecognizer) {
label.text = "Long press recognized"
// example task: show an alert
if gesture.state == UIGestureRecognizerState.began {
let alert = UIAlertController(title: "Long Press", message: "Can I help you?", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
// Pan action
#objc func handlePan(gesture: UIPanGestureRecognizer) {
label.text = "Pan recognized"
// example task: drag view
let location = gesture.location(in: view) // root view
panView.center = location
}
// Swipe action
#objc func handleSwipe(gesture: UISwipeGestureRecognizer) {
label.text = "Swipe recognized"
// example task: animate view off screen
let originalLocation = swipeView.center
if gesture.direction == UISwipeGestureRecognizerDirection.right {
UIView.animate(withDuration: 0.5, animations: {
self.swipeView.center.x += self.view.bounds.width
}, completion: { (value: Bool) in
self.swipeView.center = originalLocation
})
} else if gesture.direction == UISwipeGestureRecognizerDirection.left {
UIView.animate(withDuration: 0.5, animations: {
self.swipeView.center.x -= self.view.bounds.width
}, completion: { (value: Bool) in
self.swipeView.center = originalLocation
})
}
}
// Pinch action
#objc func handlePinch(gesture: UIPinchGestureRecognizer) {
label.text = "Pinch recognized"
if gesture.state == UIGestureRecognizerState.changed {
let transform = CGAffineTransform(scaleX: gesture.scale, y: gesture.scale)
pinchView.transform = transform
}
}
// Rotate action
#objc func handleRotate(gesture: UIRotationGestureRecognizer) {
label.text = "Rotate recognized"
if gesture.state == UIGestureRecognizerState.changed {
let transform = CGAffineTransform(rotationAngle: gesture.rotation)
rotateView.transform = transform
}
}
}
Notes
You can add multiple gesture recognizers to a single view. For the sake of simplicity, though, I didn't do that (except for the swipe gesture). If you need to for your project, you should read the gesture recognizer documentation. It is fairly understandable and helpful.
Known issues with my examples above: (1) Pan view resets its frame on next gesture event. (2) Swipe view comes from the wrong direction on the first swipe. (These bugs in my examples should not affect your understanding of how Gestures Recognizers work, though.)
I think you can simply use
UIControl *headerView = ...
[headerView addTarget:self action:#selector(myEvent:) forControlEvents:UIControlEventTouchDown];
i mean headerView extends from UIControl.
Swift 3 & Swift 4
import UIKit
extension UIView {
func addTapGesture(tapNumber: Int, target: Any, action: Selector) {
let tap = UITapGestureRecognizer(target: target, action: action)
tap.numberOfTapsRequired = tapNumber
addGestureRecognizer(tap)
isUserInteractionEnabled = true
}
}
Use
yourView.addTapGesture(tapNumber: 1, target: self, action: #selector(yourMethod))
Based on the accepted answer you can define a macro:
#define handle_tap(view, delegate, selector) do {\
view.userInteractionEnabled = YES;\
[view addGestureRecognizer: [[UITapGestureRecognizer alloc] initWithTarget:delegate action:selector]];\
} while(0)
This macro uses ARC, so there's no release call.
Macro usage example:
handle_tap(userpic, self, #selector(onTapUserpic:));
In Swift 4.2 and Xcode 10
Use UITapGestureRecognizer for to add touch event
//Add tap gesture to your view
let tap = UITapGestureRecognizer(target: self, action: #selector(handleGesture))
yourView.addGestureRecognizer(tap)
// GestureRecognizer
#objc func handleGesture(gesture: UITapGestureRecognizer) -> Void {
//Write your code here
}
If you want to use SharedClass
//This is my shared class
import UIKit
class SharedClass: NSObject {
static let sharedInstance = SharedClass()
//Tap gesture function
func addTapGesture(view: UIView, target: Any, action: Selector) {
let tap = UITapGestureRecognizer(target: target, action: action)
view.addGestureRecognizer(tap)
}
}
I have 3 views in my ViewController called view1, view2 and view3.
override func viewDidLoad() {
super.viewDidLoad()
//Add gestures to your views
SharedClass.sharedInstance.addTapGesture(view: view1, target: self, action: #selector(handleGesture))
SharedClass.sharedInstance.addTapGesture(view: view2, target: self, action: #selector(handleGesture))
SharedClass.sharedInstance.addTapGesture(view: view3, target: self, action: #selector(handleGesture2))
}
// GestureRecognizer
#objc func handleGesture(gesture: UITapGestureRecognizer) -> Void {
print("printed 1&2...")
}
// GestureRecognizer
#objc func handleGesture2(gesture: UITapGestureRecognizer) -> Void {
print("printed3...")
}
You can achieve this by adding Gesture Recogniser in your code.
Step 1: ViewController.m:
// Declare the Gesture.
UITapGestureRecognizer *gesRecognizer = [[UITapGestureRecognizer alloc]
initWithTarget:self
action:#selector(handleTap:)];
gesRecognizer.delegate = self;
// Add Gesture to your view.
[yourView addGestureRecognizer:gesRecognizer];
Step 2: ViewController.m:
// Declare the Gesture Recogniser handler method.
- (void)handleTap:(UITapGestureRecognizer *)gestureRecognizer{
NSLog(#"Tapped");
}
NOTE: here yourView in my case was #property (strong, nonatomic) IBOutlet UIView *localView;
EDIT: *localView is the white box in Main.storyboard from below
Heres a Swift version:
// MARK: Gesture Extensions
extension UIView {
func addTapGesture(#tapNumber: Int, target: AnyObject, action: Selector) {
let tap = UITapGestureRecognizer (target: target, action: action)
tap.numberOfTapsRequired = tapNumber
addGestureRecognizer(tap)
userInteractionEnabled = true
}
func addTapGesture(#tapNumber: Int, action: ((UITapGestureRecognizer)->())?) {
let tap = BlockTap (tapCount: tapNumber, fingerCount: 1, action: action)
addGestureRecognizer(tap)
userInteractionEnabled = true
}
}
Swift 3:
let tapGestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTapGestureRecognizer(_:)))
view.addGestureRecognizer(tapGestureRecognizer)
func handleTapGestureRecognizer(_ gestureRecognizer: UITapGestureRecognizer) {
}
Objective-C:
UIControl *headerView = [[UIControl alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, nextY)];
[headerView addTarget:self action:#selector(myEvent:) forControlEvents:UIControlEventTouchDown];
Swift:
let headerView = UIControl(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: nextY))
headerView.addTarget(self, action: #selector(myEvent(_:)), for: .touchDown)
The question asks:
How do I add a touch event to a UIView?
It isn't asking for a tap event.
Specifically OP wants to implement UIControlEventTouchDown
Switching the UIView to UIControl is the right answer here because Gesture Recognisers don't know anything about .touchDown, .touchUpInside, .touchUpOutside etc.
Additionally, UIControl inherits from UIView so you're not losing any functionality.
If all you want is a tap, then you can use the Gesture Recogniser. But if you want finer control, like this question asks for, you'll need UIControl.
https://developer.apple.com/documentation/uikit/uicontrol?language=objc
https://developer.apple.com/documentation/uikit/uigesturerecognizer?language=objc
Swift 5.3
Solution with Closure, based on: UIGestureRecognizer with closure
final class BindableGestureRecognizer: UITapGestureRecognizer {
private var action: () -> Void
init(action: #escaping () -> Void) {
self.action = action
super.init(target: nil, action: nil)
self.addTarget(self, action: #selector(execute))
}
#objc private func execute() {
action()
}
}
public extension UIView {
/// A discrete gesture recognizer that interprets single or multiple taps.
/// - Parameters:
/// - tapNumber: The number of taps necessary for gesture recognition.
/// - closure: A selector that identifies the method implemented by the target to handle the gesture recognized by the receiver. The action selector must conform to the signature described in the class overview. NULL is not a valid value.
func addTapGesture(tapNumber: Int = 1, _ closure: (() -> Void)?) {
guard let closure = closure else { return }
let tap = BindableGestureRecognizer(action: closure)
tap.numberOfTapsRequired = tapNumber
addGestureRecognizer(tap)
isUserInteractionEnabled = true
}
}
Using:
view.addTapGesture { [weak self] in
self?.view.backgroundColor = .red
}
Simple and Useful Extension:
extension UIView {
private struct OnClickHolder {
static var _closure:()->() = {}
}
private var onClickClosure: () -> () {
get { return OnClickHolder._closure }
set { OnClickHolder._closure = newValue }
}
func onTap(closure: #escaping ()->()) {
self.onClickClosure = closure
isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(onClickAction))
addGestureRecognizer(tap)
}
#objc private func onClickAction() {
onClickClosure()
}
}
Usage:
override func viewDidLoad() {
super.viewDidLoad()
let view = UIView(frame: .init(x: 0, y: 0, width: 80, height: 50))
view.backgroundColor = .red
view.onTap {
print("View Tapped")
}
}
Here is ios tapgesture;
First you need to create action for GestureRecognizer after write the below code under the action as shown below
- (IBAction)tapgesture:(id)sender
{
[_password resignFirstResponder];
[_username resignFirstResponder];
NSLog(#" TapGestureRecognizer tapped");
}
Another way is adding a transparent button to the view
UIButton *b = [UIButton buttonWithType:UIButtonTypeCustom];
b.frame = CGRectMake(0, 0, headerView.width, headerView.height);
[headerView addSubview:b];
[b addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchDown];
And then, handle click:
- (void)buttonClicked:(id)sender
{}
Create a gesture recognizer (subclass), that will implement touch events, like touchesBegan. You can add it to the view after that.
This way you'll use composition instead subclassing (which was the request).
Why don't you guys try SSEventListener?
You don't need to create any gesture recognizer and separate your logic apart to another method. SSEventListener supports setting listener blocks on a view to listen for single tap gesture, double tap gesture and N-tap gesture if you like, and long press gesture. Setting a single tap gesture listener becomes this way:
[view ss_addTapViewEventListener:^(UITapGestureRecognizer *recognizer) { ... } numberOfTapsRequired:1];

Resources