IOS学习之——UItouch的相关使用

来源:互联网 发布:淘宝话费充值利润 编辑:程序博客网 时间:2024/06/06 07:32



下面通过UItouch,来实现一个图片的拖拽功能,效果图如上图


#import <UIKit/UIKit.h>@interface ViewController : UIViewController{    //定义一个最后的点    CGPoint pLast;}@end


////  ViewController.m//  UItouch相关////#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    //在界面上画一个image    UIImage *imge=[UIImage imageNamed:@"welcome1"];    UIImageView *iv=[[UIImageView alloc]initWithImage:imge];        iv.frame=CGRectMake(50, 100, 300, 500);        iv.tag=101;    [self.view addSubview:iv];}//点击屏幕开始的瞬间调用此函数//一次点的过程是://state1、手指触碰屏幕//state2、手指接触到屏幕并且没有离开,按住屏幕时,包括按住并且移动手指。//state3、手指离开屏幕-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{    NSLog(@"手指触屏瞬间调用……");        //获取任意的点击对象    //一般只有一个点击对象,获得的对象就是点击对象    UITouch *touch=[touches anyObject];    if(touch.tapCount==1){//单次点击        NSLog(@"单次点击");        //连续点击,0.5秒之内算是双击    }else if(touch.tapCount==2){        NSLog(@"双击……");    }    pLast=[touch locationInView:self.view];}//state2、手指接触到屏幕并且没有离开,按住屏幕时,包括按住并且移动手指。-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{    NSLog(@"手指移动的时候……");    //获取当前触碰对象    UITouch *touch=[touches anyObject];    //获得当前坐标点    CGPoint point=[touch locationInView:self.view];    NSLog(@"当前坐标 X=%f Y=%f",point.x,point.y);        //每次移动的偏移量    float xoffset=point.x-pLast.x;    float yoffset=point.y-pLast.y;        pLast=point;//将当前拖拽的点,保存为最后的点        UIImageView *iv=[self.view viewWithTag:101];    iv.frame=CGRectMake(iv.frame.origin.x+xoffset, iv.frame.origin.y+yoffset, iv.frame.size.width, iv.frame.size.height);    }//state3、手指离开屏幕-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{    NSLog(@"手指离开屏幕时调用……");}//比如电话来了,紧急情况,触屏取消-(void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{    NSLog(@"特殊情况中断触屏事件调用…………");}- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}@end












0 0
原创粉丝点击