Skip to content

Instantly share code, notes, and snippets.

@KaneBuckthorpe
Last active April 27, 2019 01:42
Show Gist options
  • Save KaneBuckthorpe/5c70e5f79da0a4f0535279801ab19d38 to your computer and use it in GitHub Desktop.
Save KaneBuckthorpe/5c70e5f79da0a4f0535279801ab19d38 to your computer and use it in GitHub Desktop.
#import <UIKit/UIKit.h>
@interface KBForceTouchGestureRecognizer : UIGestureRecognizer
@property (nonatomic) NSUInteger numberOfTouchesRequired;
@property (nonatomic, readonly) CGFloat currentForce;
@end
@interface _UILinearForceLevelClassifier :NSObject
-(double)standardThreshold;
@end
#import "KBForceTouchGestureRecognizer.h"
#import <UIKit/UIGestureRecognizerSubclass.h>
@interface KBForceTouchGestureRecognizer ()
@property (nonatomic, readwrite) CGFloat currentForce;
@end
@implementation KBForceTouchGestureRecognizer{
_UILinearForceLevelClassifier *_forceSpecs;
}
- (id)initWithTarget:(id)target action:(SEL)action {
if (self = [super initWithTarget:target action:action]) {
self.numberOfTouchesRequired = 1.0;
_forceSpecs= [_UILinearForceLevelClassifier new];
}
return self;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[super touchesBegan:touches withEvent:event];
[self handleForceWithTouches:touches];
}
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[super touchesMoved:touches withEvent:event];
[self handleForceWithTouches:touches];
}
- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent *)event {
[super touchesEnded:touches withEvent:event];
[super setState:UIGestureRecognizerStateEnded];
}
-(void)handleForceWithTouches:(NSSet<UITouch *> *)touches{
if(touches.count!=self.numberOfTouchesRequired){
[super setState:UIGestureRecognizerStateFailed];
}
CGFloat minimumForce = _forceSpecs.standardThreshold;
UITouch *t=touches.anyObject;
self.currentForce=t.force;
if (self.currentForce >= minimumForce) {
if (super.state==UIGestureRecognizerStateBegan){
[super setState:UIGestureRecognizerStateChanged];
}
if (super.state!=UIGestureRecognizerStateChanged){
[super setState:UIGestureRecognizerStateBegan];
}
}
}
@end

Usage

KBForceTouchGestureRecognizer*forceTouchGesture=[[KBForceTouchGestureRecognizer alloc] initWithTarget:self action:@selector(handleForceTouch:)];
[self  addGestureRecognizer:forceTouchGesture];
- (void)handleForceTouch:(KBForceTouchGestureRecognizer *)sender {
	if (sender.state == UIGestureRecognizerStateBegan) {
  ///recognized- do stuff here
}
  if (sender.state == UIGestureRecognizerStateChanged) {
  ////Is recognized and changing - Do fancier stuff here
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment