iOS中三大事件(触摸、加速、远程)

iOS中的事件可以分为3大类型:

1、触摸事件

2、加速计事件(运动事件)

3、远程控制事件

一:触摸事件

// 一根或者多根手指开始触摸view,系统会自动调用view的下面方法

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;

// 一根或者多根手指在view上移动,系统会自动调用view的下面方法(随着手指的移动,会持续调用该方法)

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;

// 一根或者多根手指离开view,系统会自动调用view的下面方法

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;

// 触摸结束前,某个系统事件(例如电话呼入)会打断触摸过程,系统会自动调用view的下面方法

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;// 系统事件干扰

以上四个方法是由系统自动调用的,所以可以通过重写该方法来处理一些事件,比如:绘图。一般不用重写这些方法,因为系统给我们提供了UIGestureRecognizer手势 ,基本上能满足我们项目的需求。

1、如果两根手指同时触摸一个view,那么view只会调用一次touchesBegan:withEvent:方法,touches参数中装着2个UITouch对象。

2、如果这两根手指一前一后分开触摸同一个view,那么view会分别调用2次touchesBegan:withEvent:方法,并且每次调用时的touches参数中只包含一个UITouch对象。

3、重写以上四个方法,如果是处理UIView的触摸事件。必须要自定义UIView子类继承自UIView。因为苹果不开源,没有把UIView的.m文件提供给我们。我们只能通过子类继承父类,重写子类方法的方式处理UIView的触摸事件。

4、如果是处理UIViewController的触摸事件,那么在控制器的.m文件中直接重写那四个方法即可!

二:加速计事件(运动事件)

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event;// 开始运动

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event;// 运动结束

- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event;// 系统事件干扰

重写以上方法,可以获取系统的加速事件,比如常见微信的摇一摇:

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent*)event {

    if (motion == UIEventSubtypeMotionShake) {

        // 检测到了,手机摇一摇

    }

}

三:远程控制事件

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

比如:耳机设置音量等事件。

你可能感兴趣的:(iOS中三大事件(触摸、加速、远程))