因为uiview或者uiviewcontroller都是继承与uiresponder ,所以都有uitouch这个事件。当用户点击屏幕的时候,会产生触摸事件。
通过uitouch事件,可以监听到开始触摸、触摸移动过程、触摸结束以及触摸打断四个不同阶段的状态,在这些方法中,我们能够获取到很多有用的信息,比如触摸点的坐标、触摸的手指数、触摸的次数等等,下面通过一个小例子来说明一下。

详细代码如下:
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
/*
定义属性
*/
@interface viewcontroller ()
{
cgpoint _startpoint; //开始点击的点
cgpoint _endpoint; //结束点击的点
uilabel *_label1; //显示当前触摸的状态的标签
uilabel *_label2;
uilabel *_label3;
uilabel *_label4;
uiimageview *_imageview; //笑脸图片
}
/*
触摸事件uitouch的系列方法如下所示 <一>到<四>
*/
#pragma mark <一> 当一个或多个手指触碰屏幕时,发送touchesbegan:withevent:消息
-(void)touchesbegan:(nsset *)touches withevent:(uievent *)event
{
_label1.text = @"触摸 开始 ";
//1. 首先获取触摸屏幕的手指
uitouch * touch = [touches anyobject];
//2. 点击的当前点的坐标
cgpoint point = [touch locationinview:self.view];
_label2.text = [nsstring stringwithformat:@"当前点得坐标:x=%.1f, y=%.1f",point.x,point.y];
//4. 获取触摸屏幕的次数
int tapcount = touch.tapcount;
//5. 获取触摸屏幕的手指根数
int fingercount = touches.count;
_label3.text = [nsstring stringwithformat:@"触摸屏幕次数为%i, 触摸的手指数为%i",tapcount,fingercount];
//6. 当前视图默认只支持单点触摸 如果想添加多点触摸 必须开启多点触摸模式
self.view.multipletouchenabled = yes;
//7.1. 得到开始点击的点,得到最后点击的点,计算一下,看看做了什么操作
_startpoint = [touch locationinview:self.view];
_label4.text = @"";
}
#pragma mark <二> 当一个或多个手指在屏幕上移动时,发送touchesmoved:withevent:消息
-(void)touchesmoved:(nsset *)touches withevent:(uievent *)event
{
_label1.text = @"触摸 move...";
cgpoint point = [[touches anyobject] locationinview:self.view];
_label2.text = [nsstring stringwithformat:@"当前点得坐标:x=%.1f, y=%.1f",point.x,point.y];
}
#pragma mark <三> 当一个或多个手指离开屏幕时,发送touchesended:withevent:消息
-(void)touchesended:(nsset *)touches withevent:(uievent *)event
{
_label1.text = @"触摸 结束";
cgpoint point = [[touches anyobject] locationinview:self.view];
//3. 判断是否进入了图片范围内
if (cgrectcontainspoint(_imageview.frame, point)) {
_label2.text = @"停留在笑脸图片范围内";
}
else
{
_label2.text = @"停留在笑脸图片外面";
}
//7.2 计算开始到结束偏移量
float distancex = fabsf(point.x - _startpoint.x);
//获取手指纵向移动的偏移量
float distancey = fabsf(point.y - _startpoint.y);
_label4.text = [nsstring stringwithformat:@"x偏移了%.1f,y方向偏移了%.1f",distancex,distancey];
_startpoint = cgpointzero;
}
#pragma mark <四> 当触摸序列被诸如电话呼入这样的系统事件打断所意外取消时,发送touchescancelled:withevent:消息-(void)touchescancelled:(nsset *)touches withevent:(uievent *)event
{
_label1.text = @"触摸 取消";
}
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:http://www.cnblogs.com/jerehedu/p/4308850.html








发表评论
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。