如何将3dtouchforce添加到UIButton?

时间:2015-12-15 05:13:39

标签: uibutton ios9 3dtouch

我想在点击或拖动按钮时测量触摸力。我创建了一个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);




}

1 个答案:

答案 0 :(得分:0)

您在0.0000中收到buttonPressed因为用户在调用此手指时已经抬起手指。

你是对的,你需要在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代替。