UI控件 - 事件处理

一、iOS的事件种类

三种事件 触摸 加速计 遥控
响应者 
继承UIResponder 才能接收并处理事件


触摸
- ( void )touchesBegan:( NSSet  *)touches withEvent:( UIEvent  *)event;
- (
void )touchesMoved:( NSSet  *)touches withEvent:( UIEvent  *)event;
- (
void )touchesEnded:( NSSet  *)touches withEvent:( UIEvent  *)event;
- (
void )touchesCancelled:( NSSet  *)touches withEvent:( UIEvent  *)event;

加速计
- (
void )motionBegan:( UIEventSubtype )motion withEvent:( UIEvent  *)event NS_AVAILABLE_IOS( 3 _0);
- (
void )motionEnded:( UIEventSubtype )motion withEvent:( UIEvent  *)event NS_AVAILABLE_IOS( 3 _0);
- (
void )motionCancelled:( UIEventSubtype )motion withEvent:( UIEvent  *)event NS_AVAILABLE_IOS( 3 _0);

远程控制
- (
void )remoteControlReceivedWithEvent:( UIEvent  *)event NS_AVAILABLE_IOS( 4 _0);

UIView的触摸事件处理

一根或者多根手指放在view上,系统会自动调用view的 touchesBegan 方法
- ( void )touchesBegan:( NSSet  *)touches withEvent:( UIEvent  *)event

一根或者多根手指在view上滑动,系统会自动调用view的 touchesMoved 方法
- ( void )touchesMoved:( NSSet  *)touches withEvent:( UIEvent  *)event

一根或者多根手指离开,系统会自动调用view的 touchesEnded方法
- ( void )touchesEnded:( NSSet  *)touches withEvent:( UIEvent  *)event;
触摸结束(中断),如某个系统事件会打断触摸过程,系统会自动调用view的 touchesCancelled 方法
- ( void )touchesCancelled:( NSSet  *)touches withEvent:( UIEvent  

如果想要多手指需要设置视图多点触控
iPhone开发中避免双击

touches是个set,其中装的是UITouch对象,可以使用
UITouch  *touch = [touches  anyObject ]; 取出UITouch
UITouch保存触摸位置、时间、阶段等,每个手指产生一个UITouch对象
根据phase属性可以看触摸的阶段
根据tapCount 确定是单个手指还是两个手指

UIEvent 事件
是一个枚举类型

       在移动的时候监听,处理移动事件,在想要移动的对象所在类中重写- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event方法,改变当前类的center

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
   
    CGPoint curP = [touch locationInView:self];
   
    CGPoint preP = [touch locationInView:self];
   
    CGFloat moveX = curP.x - preP.x;
    CGFloat moveY = curP.y - preP.y;
   
    CGPoint center = self.center;
    center.x += moveX;
    center.y += moveY;
    self.center = center;
   
}

二、事件的产生和传递(找到最佳相应者)
发生触摸事件后,将事件加入一个由 UIApplication 管理的队列中
先发送事件给应用程序的主窗口
主窗口会在视图层次找到一个最合适的层处理事件

层级 : 有同一个父控件的是同一层级

UIView不接收触摸事件的几个情形
1.
 不可交互
userInteractionEnabled
  NO;

2.
 隐藏
hidden
  NO;

3.
 透明alpha  0.0   0.01

UIImageView
不能交互,因此UIImageView以及他的子控件默认是不能接收触摸事件的
UIImageView
上的按钮等也不能完成事件的处理,因为在事件传递的过程中事件传递中断,之间没传给UIImageView


原理: 触摸事件的传递过程
点击绿色的View
1 .
 触摸事件的传递是从父控件到子控件

UIApplication -> UIWindow -> 白色 -> 橙色 -> 蓝色 -> 黄色


如何找到最合适的控件处理事件?
1.
  自己是否能接收触摸事件
2.
  触摸点是否在自己身上
3 .
从后往前便利子控件( UIApplication     控制器),重复前面的两个步骤
最后的东西在最前面
4.
  如果没有符合条件的子控件,那么就自己最合合适处理


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值