I want to measure the touch force when tapping or dragging a button. i have created a UITapGestureRecognizer (for tapping) and added it to myButton like this:
UITapGestureRecognizer *tapRecognizer2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(buttonPressed:)];
[tapRecognizer2 setNumberOfTapsRequired:1];
[tapRecognizer2 setDelegate:self];
[myButton addGestureRecognizer:tapRecognizer2];
i have created a method called buttonPrssed like this:
-(void)buttonPressed:(id)sender
{
[myButton touchesMoved:touches withEvent:event];
myButton = (UIButton *) sender;
UITouch *touch=[[event touchesForView:myButton] anyObject];
CGFloat force = touch.force;
forceString= [[NSString alloc] initWithFormat:@"%f", force];
NSLog(@"forceString in imagePressed is : %@", forceString);
}
I keep getting zero values (0.0000) for touch. any help or advice would be appreciated. i did a search and found DFContinuousForceTouchGestureRecongnizer sample project but found it too complicated. I use iPhone 6 Plus s that has touch. i can also measure touch when tapping on any other area in the screen but not on buttons using this code:
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[super touchesMoved:touches withEvent:event];
UITouch *touch = [touches anyObject];
//CGFloat maximumPossibleForce = touch.maximumPossibleForce;
CGFloat force = touch.force;
forceString= [[NSString alloc] initWithFormat:@"%f", force];
NSLog(@"forceString is : %@", forceString);
}
You are getting 0.0000
in buttonPressed
because the user already lifted his finger when this is called.
You are right, that you need to get the force in the touchesMoved
method, but you need to get it in the UIButton's touchesMoved
method. Because of that you need to subclass UIButton and override its touchesMoved method:
Header file:
#import <UIKit/UIKit.h>
@interface ForceButton : UIButton
@end
Implementation:
#import "ForceButton.h"
@implementation ForceButton
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[super touchesMoved:touches withEvent:event];
UITouch *touch = [touches anyObject];
CGFloat force = touch.force;
CGFloat relativeForce = touch.force / touch.maximumPossibleForce;
NSLog(@"force: %f, relative force: %f", force, relativeForce);
}
@end
Also, there is no need to use a UITapGestureRecognizer
to detect a single tap on a UIButton
. Just use addTarget
instead.