IOS 中事件响应皆是通过
UIResponder
。我们可以执行UIResponder
协议响应事件。这里我们用UIViewController
做示例,UIViewController
默认实现UIResponder
协议。
// UIViewController.m
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {NSLog(@"屏幕被手指按下了");// 获取手指列表NSArray<UITouch*>* toucheList = [touches allObjects];for (int i = 0; i < toucheList.count; i ++) {UITouch* touch = toucheList[i];NSLog(@"获取手指15s内同一位置点击次数 -> 手指 %d 15s内点击了 %zd 次", i, touch.tapCount);}
}- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {NSLog(@"手指移动啦");// 获取手指列表UITouch* touch = [touches allObjects][0];// 获取手指相对于指定视图的x,y轴CGPoint position = [touch locationInView:self.view];NSLog(@"手指坐标为x = %f,y = %f", position.x, position.y);
}- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {NSLog(@"手指离开了");
}- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {NSLog(@"触摸过程被其他行为异常中断");
}
UIResponder 协议函数
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event
当手指触摸屏幕触发- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event
当手指触摸并产生移动触摸- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event
当手指离开屏幕触发- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event
当手指触摸过程被其他行为中断等异常情况触发- (void)pressesBegan:(NSSet<UIPress *> *)presses withEvent:(nullable UIPressesEvent *)event API_AVAILABLE(ios(9.0))
用户用力按下屏幕开始触发- (void)pressesChanged:(NSSet<UIPress *> *)presses withEvent:(nullable UIPressesEvent *)event API_AVAILABLE(ios(9.0))
用户用力按下屏幕发生压力变化触发- (void)pressesEnded:(NSSet<UIPress *> *)presses withEvent:(nullable UIPressesEvent *)event API_AVAILABLE(ios(9.0))
用户按压结束触发- (void)pressesCancelled:(NSSet<UIPress *> *)presses withEvent:(nullable UIPressesEvent *)event
用户按压行为被打断触发,IOS9以上支持- (void)motionBegan:(UIEventSubtype)motion withEvent:(nullable UIEvent *)event
陀螺仪或加速设备开始发生改变触发- (void)motionEnded:(UIEventSubtype)motion withEvent:(nullable UIEvent *)event
陀螺仪或加速设备发生改变过程触发- (void)motionCancelled:(UIEventSubtype)motion withEvent:(nullable UIEvent *)event
陀螺仪或加速设备改变过程被其他行为中断异常触发
UITouch 属性
名称 | 类型 | 说明 | 默认值 |
---|---|---|---|
timestamp | NSTimeInterval | 手指当前触摸的时间 | |
phase | UITouchPhase | 手指当前处于的行为状态 | |
tapCount | NSUInteger | 手指15秒内同一位置触摸的次数 | 0 |
type | UITouchType | 手指是间接还是直接触摸屏幕 | |
type | UITouchType | 手指是间接还是直接触摸屏幕 | |
majorRadius | CGFloat | 手指触摸屏幕的半径 | |
maximumPossibleForce | CGFloat | 设备最大压力力度 | |
maximumPossibleForce | CGFloat | 设备最大压力力度 |
UITouch API
- (CGPoint)locationInView:(nullable UIView *)view
手指当前相对于指定视图的位置- (CGPoint)previousLocationInView:(nullable UIView *)view
手指上一次相对于指定视图的位置