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

9.UITouch 保存手指的信息(触摸的点

2015-11-14 17:58 585 查看

UITouch 保存手指的信息(触摸的点)

视图触摸事件TouchView

1.首先创建一个继承于View的类

@interface TouchView : UIView

2.把根视图的View换成自定义视图TouchView

需要让TouchView 来处理事件 (响应事件)

实现响应者类中的方法 来捕获触摸事件

TouchView *touchView = [[TouchView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];

touchView.backgroundColor = [UIColor redColor];

[self.view addSubview:touchView];

3.在TouchView.m处理触摸事件

开始触摸触发这个方法

- (void)touchesBegan:(NSSet )touches withEvent:(UIEvent )event

{

NSLog(@"开始摸");


UITouch 保存手指的信息(触摸的点)

UITouch *touch = [touches anyObject];

取出当前 触摸的点

返回一个当前触摸的点 相对于传进去的参数View. selfx相当于自定的视图TouchView

CGPoint p1 = [touch locationInView:self];

NSLog(@”%@”,NSStringFromCGPoint(p1));

返回当前点的上一个的点 相对于串进去的参数View

CGPoint p2 = [touch previousLocationInView:self];

NSLog(@”%@”,NSStringFromCGPoint(p2));

}

触摸中持续触发

- (void)touchesMoved:(NSSet )touches withEvent:(UIEvent )event

{

NSLog(@”触摸中”);

UITouch 保存手指的信息(触摸的点)

UITouch *touch = [touches anyObject];

取出当前点

CGPoint p1 = [touch locationInView:self];

取出当前点的上一个点

CGPoint p2 = [touch previousLocationInView:self];

计算当前点和上一个点的X轴的偏移量

CGFloat x = p1.x - p2.x;

计算当前点和上一个点的y轴的偏移量

CGFloat y = p1.y - p2.y;

实现视图跟随触摸位置改变

self.center = CGPointMake(self.center.x + x, self.center.y + y);

实现随机变颜色

self.backgroundColor = [UIColor colorWithRed:(arc4random()% 256/255.0) green:(arc4random()%256/255.0) blue:(arc4random()%256/255.0) alpha:1];

}

(void)touchesEnded:(NSSet )touches withEvent:(UIEvent )event

{

NSLog(@”抚摸结束”);

}

(void)touchesCancelled:(NSSet )touches withEvent:(UIEvent )event

{

NSLog(@”抚摸被中断 例如触摸中来电话 可以触发中断, 例如小退出”);

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