美文网首页
UITapGestureRecognizer - 当点击的时候触

UITapGestureRecognizer - 当点击的时候触

作者: TomatosX | 来源:发表于2016-05-06 15:53 被阅读796次

    UITapGestureRecognizer - It is work when the finger touch up. But I need it work when the finger touch down, How should I do?
    We should create a custom gesture to solve the problem.

    1、Objective-C implementation:

    Create my custom TouchDownGestureRecognizer subcalss and implement gesture in touchesBegan.

    TouchDownGestureRecognizer.h

    #import <UIKit/UIKit.h>
    
    @interface TouchDownGestureRecognizer : UIGestureRecognizer
    
    @end
    

    TouchDownGestureRecognizer.m

    #import "TouchDownGestureRecognizer.h"
    #import <UIKit/UIGestureRecognizerSubclass.h>
    
    @implementation TouchDownGestureRecognizer
    -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
        if (self.state == UIGestureRecognizerStatePossible) {
            self.state = UIGestureRecognizerStateRecognized;
        }
    }
    
    -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
        self.state = UIGestureRecognizerStateFailed;
    }
    
    -(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
        self.state = UIGestureRecognizerStateFailed;
    }
    
    
    @end
    

    implementation:

    #import "TouchDownGestureRecognizer.h"
        TouchDownGestureRecognizer *touchDown = [[TouchDownGestureRecognizer alloc] initWithTarget:self action:@selector(handleTouchDown:)];
        [yourView addGestureRecognizer:touchDown];
    
    -(void)handleTouchDown:(TouchDownGestureRecognizer *)touchDown{
        NSLog(@"Down");
    }
    

    2、Swift implementation:

    import UIKit
    import UIKit.UIGestureRecognizerSubclass
    
    class TouchDownGestureRecognizer: UIGestureRecognizer
    {
        override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent)
        {
            if self.state == .Possible
            {
                self.state = .Recognized
            }
        }
    
        override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent)
        {
            self.state = .Failed
        }
    
        override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent)
        {
            self.state = .Failed
        }
    }
    

    From

    相关文章

      网友评论

          本文标题:UITapGestureRecognizer - 当点击的时候触

          本文链接:https://www.haomeiwen.com/subject/zyjjrttx.html