在Cocoa中,代表触摸对象的类是UITouch。当用户触摸屏幕后,就会产生相应的事件,所有相关的UITouch对象都被包装在事件中,被程序交由特定的对象来处理。UITouch对象直接包括触摸的详细信息。
UITouch类中包含5个属性:
window:触摸产生时所处的窗口。由于窗口可能发生变化,当前所在的窗口不一定是最开始的窗口。 view:触摸产生时所处的视图。由于视图可能发生变化,当前视图也不一定时最初的视图。 tapCount:轻击(Tap)操作和鼠标的单击操作类似,tapCount表示短时间内轻击屏幕的次数。因此可以根据tapCount判断单击、双击或更多的轻击。 timestamp:时间戳记录了触摸事件产生或变化时的时间。单位是秒。 phase:触摸事件在屏幕上有一个周期,即触摸开始、触摸点移动、触摸结束,还有中途取消。而通过phase可以查看当前触摸事件在一个周期中所处的状态。UIView类继承了UIResponder类,要对事件作出处理还需要重写UIResponder类中定义的事件处理函数。根据不同的触碰状态,程序会调用相应的处理函数,这些函数包括:
-(void) touchesBegan:(NSSet *)touches withEvents:(UIEvent *)event; //手在屏幕中
-(void) touchesMoved:(NSSet *)touches withEvents:(UIEvent *)event; //手在屏幕中移动
-(void) touchesEnded:(NSSet *)touches withEvents:(UIEvent *)event; //手离开屏幕
-(void) touchesCancelled:(NSSet *)touches withEvents:(UIEvent *)event; //无效 比如(接电话)
- 实例 一: 触摸屏幕时 图片跟着鼠标一起移动
- (void)viewDidLoad {
[super viewDidLoad];
UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(20.0, 20.0, 30.0, 30.0)];
image.image = [UIImage imageNamed:@"QQ.png"];
image.tag = 100;
[self.view addSubview:image];
}
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
NSLog(@"手在屏幕中移动");
UITouch *touch = [touches anyObject];
UIImageView *view1 = (UIImageView *)[self.view viewWithTag:100];
CGPoint point = [touch locationInView:self.view];
CGRect frame = view1.frame;
frame.origin = point;
view1.frame = frame;
}
- 实例 二: 判断 点击屏幕次数 然后改变视图元素
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
NSLog(@"手离开屏幕");
UITouch *touch = [touches anyObject];
// tapCount 判断 点击屏幕次数
if (touch.tapCount == 1) {
self.view.backgroundColor = [UIColor whiteColor];
}
if (touch.tapCount == 2) {
self.view.backgroundColor = [UIColor redColor];
}
if (touch.tapCount == 3) {
self.view.backgroundColor = [UIColor yellowColor];
}
if (touch.tapCount == 4) {
self.view.backgroundColor = [UIColor grayColor];
}
}