您的位置:首页 > 产品设计 > UI/UE

iOS开发从入门到精通--UITouch 触摸事件处理

2016-07-27 08:21 429 查看
UITouch 触摸事件处理:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController{

CGPoint  _mPtLast;
}

@end


#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:@"17_2.png"];

//创建图像视图
UIImageView * iView =[[UIImageView alloc]init];

iView.image=image;

iView.frame = CGRectMake(50, 100, 220, 300);

//将图像视图显示到屏幕上
iView.tag =101;
[self.view addSubview:iView];

}

//当点击屏幕开始的瞬间,调用此函数
//一次点击的过程
//状态1.手指触碰屏幕的瞬间
//状态2.手指接触到屏幕,并且没有离开,按住屏幕时,包括按住屏幕并且移动手指
//状态3.手指离开屏幕的瞬间

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

//获取点击对象,anyObject获取任何一个点击对象
//只有一个点击对象时,获得的对象就是我们的点击对象
UITouch * touch = [touches anyObject];

//tapCount记录当前点击次数
if(touch.tapCount==1){
NSLog(@"单次点击");
}
else if(touch.tapCount==2){
NSLog(@"双次点击");
}

_mPtLast = [touch locationInView:self.view];

NSLog(@"手指触碰瞬间!");
}

//状态2:touchesMoved
-(void) touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
NSLog(@"手指移动时!");
UITouch * touch = [touches anyObject];
//获得当前手指在屏幕上的相对坐标
//相对于当前视图的坐标
CGPoint pt = [touch locationInView:self.view];

//每次移动的偏移量大小
float xOffset = pt.x-_mPtLast.x;
float yOffset = pt.y-_mPtLast.y;

UIImageView * iView =(UIImageView *) [self.view viewWithTag:101];

_mPtLast =pt;

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

NSLog(@"X=%f , Y=%f",pt.x,pt.y);
}

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

//在特殊情况下中断触屏事件时调用,电话,紧急信息
//用来做紧急数据等处理
-(void) touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
NSLog(@"touchesCancelled");
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: