iOS学习笔记之-使用UITouch来根据手指位置移动图片

    xiaoxiao2021-03-25  81

    //

    //  ViewController.m

    //  UITouchStudy

    //

    //  Created by LiuJunHong on 17/3/9.

    //  Copyright © 2017 liujunhong. All rights reserved.

    //

    #import "ViewController.h"

    @interface ViewController ()

    @end

    @implementation ViewController

    - (void)viewDidLoad {

        [super viewDidLoad];

        // Do any additional setup after loading the view, typically from a nib.

        UIImage*image = [UIImage imageNamed:@"IMG_2117.png"];

        UIImageView*imageview = [[UIImageView alloc]init];

        imageview.image = image;

        imageview.frame = CGRectMake(50, 100, 200, 300);

        [self.view addSubview:imageview];

        imageview.tag=100;

    }

    //点击屏幕的瞬间,手指刚刚碰到屏幕

    -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

        NSLog(@"手指触碰到的瞬间");

        UITouch*touch = [touches anyObject];

        //获得当前的点击的位置

        _last = [touch locationInView:self.view ];

        //获得点击对象,单次点击只有一个对象

    //    UITouch*touch = [touches anyObject];

    //

    //    if(touch.tapCount==1){

    //    

    //        NSLog(@"1");

    //    

    //    }else if(touch.tapCount==2){

    //    

    //        NSLog(@"2");

    //    }

    }

    //手指没离开屏幕,手指在屏幕上的时候调用,可以获得手指移动时候的数据

    -(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

        UITouch*touch =[touches anyObject];

        //手指相对于当前视图的坐标

        CGPoint pt = [touch locationInView:self.view];

        //计算拖动后x方向的偏移

        float xOffset=pt.x-_last.x;

        //计算拖动后y方向的偏移

        float yOffset=pt.y-_last.y;

        NSLog(@"%f,%f",pt.x,pt.y);

        //获得图片的视图

        UIImageView * imageview  =(UIImageView*)[self.view viewWithTag:100];

        //移动的时候将手指的最后位置设置为当前手指的位置,要是不设置,偏移量始终是根据某一个位置计算,跟手指的位置就没有关系了

        _last=pt;

        //当前的imageviewxy加上偏移量,就是实际移动的位置,而不是一直手指在左上角

        imageview.frame = CGRectMake(imageview.frame.origin.x+xOffset ,imageview.frame.origin.y+yOffset, imageview.frame.size.width, imageview.frame.size.height);

        

        NSLog(@"手指移动");

    }

    //手指离开屏幕

    -(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

        NSLog(@"手指离开屏幕");

        //获得点击对象,单次点击只有一个对象

    //    UITouch*touch = [touches anyObject];

    //    

    //    if(touch.tapCount==1){

    //        

    //        NSLog(@"1");

    //        

    //    }else if(touch.tapCount==2){

    //        

    //        NSLog(@"2");

    //    }

    }

    //特殊情况,中断现在的触屏事件,比如玩游戏来电话了

    -(void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

        NSLog(@"取消点击事件");

    }

    - (void)didReceiveMemoryWarning {

        [super didReceiveMemoryWarning];

        // Dispose of any resources that can be recreated.

    }

    @end

    转载请注明原文地址: https://ju.6miu.com/read-21724.html

    最新回复(0)