0

我想在点击或拖动按钮时测量触摸力。我创建了一个 UITapGestureRecognizer (用于点击)并将其添加到 myButton 中,如下所示:

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




}
4

1 回答 1

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

此外,无需使用 aUITapGestureRecognizer来检测对 a 的单击UIButton。改用就好addTarget了。

于 2015-12-15T08:43:22.927 回答