美文网首页iOS之OC深入理解iOSiOS Developer
iOS中事件处理机制——触摸、手势、控制

iOS中事件处理机制——触摸、手势、控制

作者: 猿来如此 | 来源:发表于2016-10-27 15:49 被阅读135次

    响应者链

    首先,想要理解事件的处理机制必须要知道iOS中响应者链,要明白事件是怎么传递的。


    Snip20161027_3.png

    如上图,假设我们点击viewC,系统会从顶层baseView开始寻找,发现点击事件在baseView或者其子类里;baseView的子类有viewA和viewB,然后从viewA和viewB中寻找,发现点击事件在viewB或者其子类里;viewB的子类为viewC和viewD,再从viewC和viewD中寻找,此时发现点击事件在viewC中,并且viewC没有子类,所以viewC响应并处理此点击事件,也就是hit-test view。

    注意点:1.如果子视图的Frame超过父视图的Frame,那么点击子视图中超出的部分,不会触发响应时间。2.只有继承于UIResponder类的对象才能处理事件。例如: UIView、UIViewContronler、UIApplication等。

    iOS常用事件处理包括:1.触摸事件;2.手势识别;3.运动事件;4.远程控制。

    一、触摸事件

    #pragma mark - 触摸事件
    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
    {
        //开始触摸时执行
    }
    - (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
    {
        //手指在屏幕上移动时执行,此方法在移动过程中重复调用
    }
    - (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
    {
        //触摸结束时执行
    }
    - (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
    {
        //触摸意外取消时执行(例如:正在触摸时打入电话等)
    }
    

    二、手势识别

    1、UITapGestureRecognizer 点按手势
    2、UIPinchGestureRecognizer 捏合手势
    3、UIPanGestureRecognizer 拖动手势
    4、UISwipeGestureRecognizer 轻扫手势
    5、UILongPressGestureRecognizer 长按手势
    6、UIRotationGestureRecognizer 旋转手势

    UIGestureRecognizer类中一些常用的属性、方法:
    属性:

    1、@property(nonatomic,readonly) UIGestureRecognizerState state;//手势状态
    2、@property(nonatomic, getter=isEnabled) BOOL enabled; // default is YES.手势是否可用
    3、@property(nullable, nonatomic,readonly) UIView *view;//触发手势的视图

    方法:

    1、- (instancetype)initWithTarget:(nullable id)target action:(nullable SEL)action ;
    2、- (void)addTarget:(id)target action:(SEL)action;
    3、- (void)removeTarget:(nullable id)target action:(nullable SEL)action;
    4、- (void)requireGestureRecognizerToFail:(UIGestureRecognizer *)otherGestureRecognizer;//指定一个手势需要另一个手势执行失败后才会执行(用来解决手势间的冲突)
    5、- (CGPoint)locationInView:(nullable UIView*)view;//在指定视图中的相对位置
    6、- (NSUInteger)numberOfTouches;//触摸点的个数
    7、- (CGPoint)locationOfTouch:(NSUInteger)touchIndex inView:(nullable UIView*)view;//触摸点相对于指定视图的位置

    三、运动事件

    1、- (void)motionBegan:(UIEventSubtype)motion withEvent:(nullable UIEvent *)event ;
    2、- (void)motionEnded:(UIEventSubtype)motion withEvent:(nullable UIEvent *)event ;
    3、- (void)motionCancelled:(UIEventSubtype)motion withEvent:(nullable UIEvent *)event ;

    四、远程控制

    - (void)remoteControlReceivedWithEvent:(nullable UIEvent *)event;

    相关文章

      网友评论

        本文标题:iOS中事件处理机制——触摸、手势、控制

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