在操作手机时,经常会有各种操作,在iOS中,就会用事件来处理这些操作(应该叫响应)。
UIEvent,事件,就是硬件捕捉一个用户的操作设备的对象。
iOS事件分为三类:触摸事件,晃动事件,远程控制事件
触摸事件:用户通过触摸屏幕触摸设备操作对象,输入数据。
实现触摸,就是iOS的UIView继承于UIResponder,支持多点触摸。所以,只要继承于UIview的所有视图,都可以响应触摸方法。
触摸处理,其实就是实现几个方法即可。
开始触摸:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
在开始触摸屏幕时,就会执行这个方法,因此,想要在触摸屏幕时,实现一些功能,或者提示,都可以在这个方法里添加。
NSSet集合里放着对象,就是UITouch对象。对象里包含这个触摸事件的情况,包括所在的window的frame,所在的视图的frame,所在window的位置,所在视图的位置等等。
event包含了这次触摸事件的事件。包括触摸事件的类型(开始触摸?触摸移动?)以及触摸所在的哪个window,哪个view和所在window和view的位置。
触摸移动:
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
在屏幕上滑动时,就是会执行这个方法。
touches和event与开始触摸方法一样的意思。
触摸结束:
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
触摸事件结束所掉方法。
取消触摸:
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
取消触摸所调方法。
一个例子:
让一个视图,随着触摸移动而移动:
NewView.m
这个视图是我们自己定义的视图。也就是视图控制器控制的子视图。由于AppDelegate和ViewController与前面的写法一样,就不写出来了。
#import "NewView.h"
#import "MyView.h"
@interface NewView ()
// 保存起始点
@property(nonatomic,assign)CGPoint point;
// 保存开始frame的点
@property(nonatomic,assign)CGPoint framepoint;
@end
@implementation NewView
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
}
return self;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
// 保存手指第一次触碰位置
self.point = [touch locationInView:self.superview];
// frame的第一次位置
self.framepoint = self.frame.origin;
NSLog(@"%@",NSStringFromCGPoint(self.point));
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
CGPoint movepoint = [touch locationInView:self.superview];
CGFloat detailX = movepoint.x - self.point.x;
CGFloat detailY = movepoint.y - self.point.y;
self.frame = CGRectMake(self.framepoint.x+detailX, self.framepoint.y+detailY, CGRectGetWidth(self.frame), CGRectGetHeight(self.frame));
self.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1];
NSLog(@"%@",NSStringFromCGPoint(self.point));
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
}
-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event{
}
@end