2015-12-15 74 views
0

我想在点击或拖动按钮时测量触摸力。我创建了一个UITapGestureRecognizer(窃听),并将其添加到myButton的是这样的:如何将3Dtouchforce添加到UIButton?

UITapGestureRecognizer *tapRecognizer2 = [[UITapGestureRecognizer  alloc] initWithTarget:self action:@selector(buttonPressed:)]; 

     [tapRecognizer2 setNumberOfTapsRequired:1]; 
     [tapRecognizer2 setDelegate:self]; 
     [myButton addGestureRecognizer:tapRecognizer2]; 

我创建了一个名为方法buttonPrssed这样的:

-(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); 

} 

我不断收到零个值(0.0000)为触摸。任何帮助或建议,将不胜感激。我做了一个搜索,发现DFContinuousForceTouchGestureRecongnizer示例项目,但发现它太复杂了。我使用具有触摸功能的iPhone 6 Plus。在屏幕上,但不使用该代码的按钮上任何其他地区攻丝时,我还可以测量触摸:

- (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); 




} 

回答

0

你得到0.0000buttonPressed,因为用户已经解除了他的手指时,这就是所谓的。

你说得对,你需要在touchesMoved方法中得到力,但是你需要在UIButton的touchesMoved方法中得到它。因此,你需要继承的UIButton并覆盖其touchesMoved方法:

头文件

#import <UIKit/UIKit.h> 

@interface ForceButton : UIButton 

@end 

实现:

#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 

而且,也没有必要使用UITapGestureRecognizer检测单击一个UIButton。改用addTarget

+0

THX joern,会尝试一下,让你知道... –

+0

Joern,我也跟着你的脚步,创造了forceButton作为子类的UIButton。我想要测量触摸力的按钮称为myButton。我添加了一个目标:[myButton addTarget:self action:@selector(buttonClicked :) forControlEvents:UIControlEventTouchUpInside];我创建了一个名为 - (void)buttonPressed:(id)sender 但我如何从buttonButton方法中的forceButton调用方法touchesMoved? –

+0

@JeffSab:你永远不会自己叫'touchesMoved'。只要用户触摸按钮,手指就会自动调用该方法,手指在该触摸过程中稍稍移动(它总是在实际设备上执行)。 – joern