IOS (补充)触摸事件处理

[1]事件的基本概念

UIEvent:事件,是由硬件捕捉的一个表示用户操作设备的对象。

分三类:触摸事件、晃动事件、远程控制事件

触摸事件:用户通过触摸设备屏幕操作对象、输入数据。支持多点触摸,包括1个到多个触摸点

UIView支持触摸事件(由于继承于UIResponder),并且支持多点触摸。

须要定义UIView子类,实现触摸相关的方法。

touches..began

touches..moved

touches...ended

touches..canceled 

[2]手势:有规律的触摸。

UITouch代表触摸在屏幕上的一根手指。

能够获取触摸时间和触摸位置。

怎样获取touch对象。touches集合中包括了视图上的全部⼿势

什么是响应者链

响应者链就是多个响应者对象组成的链

事件的基本概念

UIEvent:事件,是由硬件捕捉的一个表示用户操作设备的对象。

分三类:触摸事件、晃动事件、远程控制事件

触摸事件:用户通过触摸设备屏幕操作对象、输入数据。

支持多点触摸,包括1个到多个触摸点

UIView支持触摸事件(由于继承于UIResponder),并且支持多点触摸。

须要定义UIView子类,实现触摸相关的方法。

touches..began

touches..moved

touches...ended

touches..canceled 

手势:有规律的触摸。

UITouch代表触摸在屏幕上的一根手指。能够获取触摸时间和触摸位置。

怎样获取touch对象。

touches集合中包括了视图上的全部⼿势

[3]什么是响应者链

响应者链就是多个响应者对象组成的链

UIResponder。响应者类。

iOS中全部能响应事件(触摸、晃动、远程事件)的对象都是响应者。

系统定义了一个抽象的父类UIResponder来表示响应者。其子类都是响应者 

硬件检測到触摸操作,会将信息交给UIApplication,開始检測。

UIApplication -> window -> viewController -> view -> 检測全部⼦子视图

终于确认触摸位置,完毕响应者链的查询过程

检測到响应者后,实现touchesBegan:withEvent:等方法,即处理事件。

 假设响应者没有处理事件,事件会向下传递。

假设没有响应者处理, 则丢弃触摸事件。

事件处理的顺序与触摸检測查询相反。
触摸的⼦视图
-> view -> viewController -> window -> UIApplication 

响应者链能够被打断。⽆法完毕检測查询过程。

视图类的属性 : userInteractionEnabled

关闭后能阻断查询过程。 

代码:

#import "TestView.h"
#import "RootView.h"
#define KRandomColor arc4random()%256/255.0
@interface TestView()
{
    //開始触摸的点

    CGPoint _start;
}
@end
@implementation TestView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {


        
        self.backgroundColor = [UIColor redColor];
    }
    return self;
}
//開始触摸事件的时候,运行touch 里面的预定的运行事件代码(開始触摸的时候,到这看看)
//一次触摸事件发生时,该方法仅仅运行一次
-(void)touchesBegan:(NSSet *)touches
          withEvent:(UIEvent *)event
{
    //触摸的时候随机颜色(KRandomColor是在延展里定义的随机数)
    self.backgroundColor = [UIColor colorWithRed:KRandomColor green:KRandomColor blue:KRandomColor alpha:1];
    //第一次触摸时候的坐标
   _start = [[touches anyObject] locationInView:self];
    NSLog(@"点我改变颜色");
}



//一次触摸事件尚未结束,会一直调用该方法
//没摸完,就一直摸
-(void)touchesMoved:(NSSet *)touches
          withEvent:(UIEvent *)event
{
    //移动的点
    CGPoint nowPoint = [[touches anyObject] locationInView:self];
    //移动的点减去開始触摸的点
    CGFloat x = nowPoint.x - _start.x;
    CGFloat y = nowPoint.y - _start.y;
    CGPoint centerPoint = CGPointMake(self.center.x + x, self.center.y + y);
    self.center = centerPoint;
    //打印移动时候的坐标
    NSLog(@"%@",NSStringFromCGPoint(nowPoint));
}


//一次触摸时间结束,运行该方法
//触摸完毕

-(void)touchesEnded:(NSSet *)touches
          withEvent:(UIEvent *)event
{
    
    NSLog(@"结束了");
}
//触摸时间被别的打断,
//有人打搅
-(void)touchesCancelled:(NSSet *)touches
              withEvent:(UIEvent *)event
{
    
}






@end






【推广】 免费学中医,健康全家人
原文地址:https://www.cnblogs.com/yjbjingcha/p/8428154.html