UISB UITouch

ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
{
    
    CGPoint _mPtLast;
    
}

@end

ViewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //加载一张图片大屏幕上
    UIImage* image =[UIImage imageNamed:@"a.jpg"];
    
    //创建图像视图
    UIImageView* iView = [[UIImageView alloc]init ];
    
    iView.image= image;
    iView.frame=CGRectMake(100, 100, 250, 250);
    iView.tag=101;
    //将图像视图显示到屏幕上
    [self.view addSubview:iView];
    
    
    
}
//当点击屏幕开始的瞬间 调用函数
//一次点击的过程
//1.手指触碰屏幕
//2.手指触碰到屏幕没有离开 按住屏幕时
//3.手指离开屏幕的瞬间

//touchesBegan 在状态一被触发
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    
    //获取点击对象 anyObject获取任何一个点击对象
    //tapCount 记录当前点击的次数
    UITouch* touch = [touches anyObject];
    if (touch.tapCount==1)
    {
        NSLog(@"单次点击");
        
    }
    else if (touch.tapCount==2)
    {
        NSLog(@"双次点击");
    }
    
    _mPtLast=[touch locationInView:self.view];
    NSLog(@"手指触碰瞬间");
    
}

//手指在屏幕上时调用 并且移动数据获取
//touchesMoved 在状态二被触发
-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    
    UITouch* touch = [touches anyObject];
    CGPoint pt = [touch locationInView:self.view];
    
    //每次移动大小的偏移量大小
    float xOffset = pt.x - _mPtLast.x;
    float yOffset = pt.y - _mPtLast.y;
    
    
    _mPtLast=pt;
    
    UIImageView* iView=(UIImageView*)[self.view viewWithTag:101];
    

    NSLog(@"x = %f ,y=%f",pt.x,pt.y);
    iView.frame=CGRectMake(iView.frame.origin.x+xOffset, iView.frame.origin.y+yOffset, iView.frame.size.width, iView.frame.size.height);
    
    
    
    NSLog(@"手指移动时");
    
}

//touchesBegan 在状态三触发
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    
    NSLog(@"手指离开屏幕");
    
}

//touchesCancelled t特殊情况屏幕触发事件
//电话 紧急求救时 取消当前点击手势调用
//用来紧急处理
-(void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    
    NSLog(@"touchesCancelled");
    
}


@end
原文地址:https://www.cnblogs.com/zhangqing979797/p/13688052.html