2015-12-15 82 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