01-事件处理简介/UIView拖拽

1.ios当中常见的事件?
        触摸事件
        加速计事件
        远程控制事件
2.什么是响应者对象?
    继承了UIResponds的对象我们称它为响应者对象 UIApplication、UIViewController、UIView都继承 UIResponder,因此它们都是响应者对象,都能够接收并处理事件.
3.为什么说继承了UIResponder就能够处理事件?
原因:因为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;
    - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event;
    - (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event;

  远程控制事件会调 :
    - (void)remoteControlReceivedWithEvent:(UIEvent *)event;
    
4.如何监听UIView的触摸事件?

    想要监听UIViiew的触摸事件, 先第一步要自定义UIView, 因为只有实现了UIResponder的事件方法才能够监听事件.
    UIView的触摸事件主要有:
    1)单根或者多根手指开始触摸view,系统会自动调用view的下方法.
    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
     2)单根或者多根手指在view上移动时,系统会自动调用view的下列方法 (随着手指的移动,会持续调用该方法,也就是说这个方法会调用很多次)
    - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
     3)单根或者多根手指离开view,系统会自动调用view的下列方法
    - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
    
5.UIView拖拽思路?
    1.定义UIView,实现监听方法.
    2.确定在TouchMove方法当中进行操作,因为用户手指在视图上移动的时候才需要移动视图。
    3.获取当前手指的位置和上一个手指的位置.
    4.当前视图的位置 = 上一次视图的位置 - 手指的偏移量

6.实现关键代码:
    当手指在屏幕上移动时持续调用
    NSSet: 它的元素都是无序的.
    NSArray: 它的是有顺序的.
    -(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    1.获取手指的对象
    UITouch *touch = [touches anyObject];
    2.获取当前手指所在的点.
    CGPoint curP = [touch locationInView:self];
    3.获取手指的上一个点.
    CGPoint preP = [touch previousLocationInView:self];
    //X轴方向偏移量
    CGFloat offsetX = curP.x - preP.x;
    //Y轴方向偏移量
    CGFloat offsetY = curP.y - preP.y;
    CGAffineTransformMakeTranslation:
    //会清空上一次的形变,相对初始位置进行形变.
    self.transform = CGAffineTransformMakeTranslation(offsetX,0);
    //相对上一次的位置进行形变.
    self.transform = CGAffineTransformTranslate(self.transform, offsetX, offsetY);
    }

原文地址:https://www.cnblogs.com/zhoudaquan/p/5037386.html