今天学习了一下触摸事件,下面打下代码测试下。
UIView中有很多触摸事件的方法,我们只要覆盖它就能执行相应操作。有触摸开始的方法,有触摸移动的方法,还有触摸结束的方法。
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
首先我们建一个项目,然后新建一个类继承于UIView,然后我们再这个视图中再添加一个小的子视图。
//插入子视图
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
view.backgroundColor = [UIColor redColor];
view.tag = 100;
[self addSubview:view];
接着,我们覆盖触摸开始的方法,在里面实现操作,改变子视图颜色。其中通过tapCount方法获得点击次数,来判断单击还是双击。
//点击开始
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//获得点击
UITouch *touch = [touches anyObject];
//计数
int count = touch.tapCount;
//单击
if (count==1) {
//延迟0.5秒执行单击方法
[self performSelector:@selector(singleTap) withObject:nil afterDelay:0.5];
}
else if(count==2){
//取消单击方法
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(singleTap) object:nil];
//执行双击方法
[self doubleTap];
}
}
单击方法要延迟执行,因为要判断是否是双击,如果双击,就取消单击方法的执行。
下面编写单击方法和双击方法,它们会改变让子视图有不同颜色。
//单击方法
-(void)singleTap{
NSLog(@"单击");
UIView *view = [self viewWithTag:100];
view.backgroundColor = [UIColor blueColor];
}
//双击方法
-(void)doubleTap{
NSLog(@"双击");
UIView *view = [self viewWithTag:100];
view.backgroundColor = [UIColor redColor];
}
我们做一个触摸移动时的操作。让子视图随着触摸而移动。
//触摸移动
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
//获得当前触摸的坐标
CGPoint point = [touch locationInView:self];
UIView *view = [self viewWithTag:100];
CGRect frame = view.frame;
frame.origin = point;
//设置坐标
view.frame = frame;
}
通过locationInView:方法获得触摸的坐标,然后改变子视图的坐标。
最后,我们在应用程序的代理类中创建视图。
MainView *view = [[MainView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame];
view.backgroundColor = [UIColor yellowColor];
[self.window addSubview:view];
运行,当我们单击时,子视图变成蓝色,双击变成红色。点击并移动,子视图也会跟着移动。
运行结果截图: