UIViewController继承自UIResponder
UIResponder中针对触摸事件声明了4个主要方法:
//当点击屏幕的开始瞬间调用此方法
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
//手指在屏幕上时调用(包括滑动)
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
//手指离开屏幕时调用
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
//特殊情况中断触屏事件时调用,例如电话中断了游戏
- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
根据以上四个方法,设计一个图片视图随手指触屏事件变化的例子:
ViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
UIImage *image = [UIImage imageNamed:@"icon1"];
UIImageView *iView = [[UIImageView alloc]initWithImage:image];
iView.frame = CGRectMake(50, 100, 220, 300);
iView.tag =101;
[self.view addSubview:iView];
}
//当点击屏幕的开始瞬间调用此方法
//一次点击的过程
//1,手指触碰屏幕 touchesBegan
//2,手指接触到屏幕并且没有离开,按住屏幕时(包括滑动)
//3,手指离开屏幕的瞬间
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event{
//获取点击对象,anyObject获取任何一个点击对象
//只有一个点击对象,获得的对象就是点击对象
UITouch* touch = [touches anyObject];
if(touch.tapCount == 1){
NSLog(@"单次点击");
}
else if(touch.tapCount == 2){
NSLog(@"双次点击");
}
NSLog(@"手指触碰瞬间");
_lastPoint = [touch locationInView:self.view];
}
//手指在屏幕上时调用
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event{
UITouch *touch = [touches anyObject];
CGPoint pt = [touch locationInView:self.view];
NSLog(@"x = %f, y = %f",pt.x,pt.y);
//每次移动的偏移量
float xOffset = pt.x -_lastPoint.x;
float yOffset = pt.y - _lastPoint.y;
UIImageView *iView = (UIImageView*)[self.view viewWithTag:101];
iView.frame = CGRectMake(iView.frame.origin.x+xOffset, iView.frame.origin.y+yOffset, iView.frame.size.width, iView.frame.size.height);
_lastPoint = pt;
//NSLog(@"手指滑动");
}
//手指离开屏幕时
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event{
NSLog(@"手指离开屏幕");
}
//特殊情况中断触屏事件时调用,例如电话中断了游戏
- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event{
}