本节学习内容:
1.UITouch的基本概念
2.UITouch的作用周期
3.UITouch的应用
【viewController.h】
#import<UIKit/UIKit.h>
@interface ViewController:UIViewController{
CGPoint mptLast;
}
【ViewController.m】
-(void)viewDidLoad{
UIImage *image=[UIImage imageNamed:@"17_2.jpg"];
UIImageView* iView=[[UIImageView alloc]init];
iView.image=image;
iView..frame=CGRectMake(50,100,220,300);
iView.tag=101;
[self.view addSubview:iView];
}
//当点击屏幕开始的瞬间调用此函数,
//一次点击的过程,
//1.手指触碰屏幕的瞬间touchesBegan
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//获取点击对象,anyObjects获取任何一个点击对象
//一般情况下只有一个点击对象,获得的对象就是我们的点击对象
UITouch* touch=[touches anyObject];
//tapcoun记录当前点击的次数
if(touch.tapcount==1){
NSLog(@"单次点击!");
}else if(touch.tapcount==2){
NSLog(@"双次点击!");
}
//记录点击的位置
_mPtLast=[touch locationInView:self.view];
NSLog(@"手指触砬瞬间!");
}
//2.手指接触到屏幕且没有离开,按住屏幕时,包括按住屏幕并且移动手指时调用
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch* touch=[touches anyObject];
//获得当前手指在屏幕上的相对坐标,相对于当前视图坐标
CGPoint pt=[touch locationInView:self.view];
UIImageView* iView=[UIImageView*)[self.view viewWithTag:101];
_mPtLast=pt;
//每次移动的偏移量大小
float xOffset=pt.x-_mPtLast.x;
float fOffset=pt.f-_mPtLast.f;
//打印坐标移动位置
NSLog(@"手指移动时! X=%f,Y=%f",pt.x,pt.y);
//图片随手指移动
//iView.frame=CGRectMake(pt.x,pt.y,iView.frame.size.width,iView.frame.size.height));
iView.frame=CGRectMake(iView.frame.origin.x+xOffset,
iView.frame.origin.y+yOffset,
iView.frame.size.width,
iView.frame.size.height);
}
//3.手指离开屏幕的瞬间调用
-(void)touchesEnded:(NSSet*)touches withEvent:(UIEvent *)event{
NSLog(@"手指离开屏幕!");
}
//4.在特殊情况中断触屏事件时调用,
//电话,紧急信息时,取消当前的点击手势作用时调用
//用来做紧急数据处理
-(void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent *)event{
NSLog(@"touch cancel!");
}
网友评论