本篇文章主要介绍了"ios触摸事件四:触摸",主要涉及到方面的内容,对于IOS开发感兴趣的同学可以参考一下:
前面了解了触摸发生的相关类与方法,然后就是触摸事件的处理了。触摸事件的处理就比较简单。重写Respond的四个方法即可。
当然前提是该控件是可以响应触摸事件的。...
前面了解了触摸发生的相关类与方法,然后就是触摸事件的处理了。触摸事件的处理就比较简单。重写Respond的四个方法即可。
当然前提是该控件是可以响应触摸事件的。一般情况继承UIRespond的控件都可以响应触摸事件。然而仍然有一些控件比较特殊,不可以响应,比如默认UIImageView、UILabel控件不可接触等。
UIView不接受触摸事件的三种情况:
- 不接受用户交互:userInteractionEnable = NO; (例如:UILabel、UIImageView这些控件,userInteractionEable默认就是NO,因此这些控件默认是不能接受触摸事件的)
- 隐藏:hidden = YES; 隐藏则用户触摸不到啊。。
- 透明:alpha = 0.0f ~0.01f ,相当于隐藏了控件
响应触摸的方法:如果希望自定义的控件可以响应用户的触摸事件,则重写UIRespond的以下四个方法来实现
`
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
//当用户手指开始触碰控件时激发该方法
-(void)touchesMoved:(NSSet )touches withEvent:(UIEvent )event;
//当用户手指在控件上移动时出发该方法
-(void)touchesEnded:(NSSet )touches withEvent:(UIEvent )event;
//当用户手指结束触摸该控件(抬起手指)时激发该方法
-(void)touchesCancelled:(NSSet )touches withEvent:(UIEvent )event;
//手势取消函数。当系统事件(比如内存不足,电话呼入)终止了触摸事件时激发该方法
`
获取触摸事件的坐标:

示例:

关键代码:
#pragma mark -触摸事件的生命周期//开始触摸
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
//返回与当前接收者有关的所有的触摸对象(同时触摸控件的手指数量)
NSSet *allTouches = [event allTouches];
NSLog(@"%li个手指触摸", allTouches.count);
NSArray *allTouch = [allTouches allObjects];
NSLog(@"event中的allTouches:%d, %@", allTouch.count, allTouch);
NSLog(@"参数touches:%d, %@", [touches allObjects].count, [touches allObjects]);
//取出任意一个触摸对象
UITouch *touch = [allTouches anyObject];
//返回触摸点在视图中的坐标CGPoint point = [touch locationInView:[touch view]];
float x = point.x;
float y = point.y;
//创建一个图画
imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,10,7)];
imgView.image = [UIImage imageNamed:@"a0_.9.png"];
//设置图片的中心坐标为触摸的点坐标
imgView.center = point;
[[touch view] addSubview:imgView];
imgView.center = point;
imgView.hidden = NO;
NSLog(@"touch(x,y) is (%.2f, %.2f)", x, y);
}
//触摸移动
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
NSSet *allTouch = [event allTouches];
UITouch *touch = [allTouch anyObject];
CGPoint point = [touch locationInView:[touch view]];
// imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,10,7)];// imgView.image = [UIImage imageNamed:@"a0_.9.png"];// imgView.center = point;// [[touch view] addSubview:imgView]; imgView.center = point;
NSLog(@"触摸移动");
}
//触摸结束
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
//[imgView removeFromSuperview];// imgView.hidden = YES;NSLog(@"触摸结束");
}
//由于外界原因(内存不足等)导致触摸取消
-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event{
}
补充:有时候我们需要判断是单击还是双击,自然而然我们会想到判断点击的次数:touch.tapCount, 但是仅此我们并不能完美完成,因为这会再点击第二次的时候进入第一次点击的效果。因此我们需要一种延迟执行的方法: