平常我们用手机的时候,手机是怎么通过我们点击来做出相对应的反应呢,这篇就来介绍触摸反应:
在UITouch最重要的三个方法就是:
1.touchesBegan(触摸开始)
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
// UITouch 保存手指信息(触摸的点)
UITouch *touch = [touches anyObject];
// 了解一下touch信息
/*
<UITouch: 0x7fd83ac41b40>
phase: Began tap count: 1
window: <UIWindow: 0x7fd83ac48e30;
frame = (0 0; 375 667); (模拟器大小)
gestureRecognizers = <NSArray: 0x7fd83ac49fe0>;
layer = <UIWindowLayer: 0x7fd83ac49230>>
view: <TouchView: 0x7fd83ae7b350;(触摸的视图)
frame = (100 100; 50 50); (触摸视图的view)
layer = <CALayer: 0x7fd83ae2ae40>>
location in window: {140, 126} (当前触摸的点相对于window的坐标)
previous location in window: {140, 126} (保存触摸的上一个点相对于window坐标)
location in view: {40, 26} (当前触摸的点相对于view的坐标)
previous location in view: {40, 26} (保存触摸的上一个点相对于view的坐标)
*/
// 取出当前触摸的点
// 返回一个当前触摸的点 相对于传进去的参数view
CGPoint p1 = [touch locationInView:self];
// 返回当前点的上一个点 相对于传进去的参数
CGPoint p2 = [touch previousLocationInView:self];
}
2.touchesMoved(触摸移动)
比如我们想移动一个view且移动的时候改变他的颜色
UITouch *touch = [touches anyObject];
// 取出当前点
// 取出当前点的上一个点
// 计算X轴偏移量
// 计算Y轴偏移量
// 改变视图原来的终点
// 返回当前点的上一个点 相对于传进去的参数
CGPoint p2 = [touch previousLocationInView:self];
// 返回一个当前触摸的点 相对于传进去的参数view
CGPoint p1 = [touch locationInView:self];
self.center = CGPointMake(self.center.x + p1.x - p2.x, self.center.y + p1.y - p2.y);
// 随机变颜色
// [0 - 255] 三原色填0~1的小数(arc4random()%256/255.0)
self.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1];
// 三原色加透明度
3.touchesEnded 触摸停止
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
}
4.touchesCancelled触摸中断
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
触摸被中断 例如触摸中来电话,小退出 可以触发中断这个方法
}
而平常我们的摇一摇屏幕手机就接收命令来做出对应动作的是哪个命令呢?
1.motionBegan 屏幕晃动的开始
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
}
2.motionEnded 晃动结束
一般都是晃动结束执行指令,如果你想在什么时候执行指令就写在哪个方法里
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
// 晃动结束跳转界面
SecondViewController *secondVC = [[SecondViewController alloc] init];
// 跳转
[self presentViewController:secondVC animated:YES completion:nil];
[secondVC release];
}
3.motionCancelled 晃动中断
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
}
我们的手机晃动,触摸接收指令是有一个顺序的,这个顺序就是我们的响应者链:
响应者链 分为两个过程
1.查询过程
当你点击屏幕,先定位到应用程序 -> window -> 控制器 -> self.view -> view上的子视图一一查找 -> 定位到被点击的子视图 查询过程结束
2.响应过程
首先看本视图能不能处理事件(实现了touchBegan等方法 就叫做可以处理事件) -> 父视图 ->
一层一层往下看能不能处理,知道window,如果都不能处理,改次点击时间被遗弃 (无效点击)
注意:
默认关闭交互的控件:UILabel UIImageView
如果需要打开交互:
可以写一个,YES为关闭,除了以上两个其余默认是开启的
view.userInteractionEnabled = NO;