iOS开发之触摸事件以及手势

2020-01-14 22:24:54刘景俊
这篇文章主要为大家详细介绍了iOS开发之触摸事件以及手势的相关资料,感兴趣的小伙伴们可以参考一下  

iOS中的事件分为三类:触摸事件、加速计事件、远程控制事件。只有继承了UIResponder的对象才能接收并处理事件,称之为“响应者对象”。UIApplication、UIViewController、UIView都继承自UIResponder。UIResponder内部提供的方法来处理事件:

触摸事件:touchesBegan、touchesMoved、touchesEnded、touchesCancelled

加速计事件:motionBegan、motionEnded、motionCancelled

远程控制事件:remoteControlReceivedWithEvent

UIVeiw的触摸事件处理过程:


/**
 * 当手指开始触摸view时调用
 *
 * @param touches <#touches description#>
 * @param event  <#event description#>
 */
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
   
  NSLog(@"%s",__func__);
}
 
/**
 * 当手指在view上移动时调用
 *
 * @param touches <#touches description#>
 * @param event  <#event description#>
 */
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
  NSLog(@"%s",__func__);
}
 
/**
 * 当手指离开view时调用
 *
 * @param touches <#touches description#>
 * @param event  <#event description#>
 */
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
   
  NSLog(@"%s",__func__);
}
 
/**
 * 当触摸事件被系统事件打断时调用
 *
 * @param touches <#touches description#>
 * @param event  <#event description#>
 */
- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
   
  NSLog(@"%s",__func__);
}

一次触摸动作必然会调用touchesBeagn、touchesMoved和touchesEnded这三个方法。

说到这几个触摸方法,首先要知道UITouch这个对象。当一根手指触摸屏幕时就会产生一个与之关联的UITouch对象,一根手指对应一个UITouch对象。这个对象里面保存着这次触摸的信息,比如触摸的位置,时间,阶段等,当手指移动时,系统会更新同一个UITouch对象。使其能一直保存该手指所在的触摸位置信息。当手指离开屏幕时,系统会销毁对应的UITouch对象。


@interface UITouch : NSObject
 
@property(nonatomic,readonly) NSTimeInterval   timestamp;
@property(nonatomic,readonly) UITouchPhase    phase;
@property(nonatomic,readonly) NSUInteger     tapCount;  // touch down within a certain point within a certain amount of time
 
// majorRadius and majorRadiusTolerance are in points
// The majorRadius will be accurate +/- the majorRadiusTolerance
@property(nonatomic,readonly) CGFloat majorRadius NS_AVAILABLE_IOS(8_0);
@property(nonatomic,readonly) CGFloat majorRadiusTolerance NS_AVAILABLE_IOS(8_0);
 
@property(nullable,nonatomic,readonly,strong) UIWindow            *window;
@property(nullable,nonatomic,readonly,strong) UIView             *view;
@property(nullable,nonatomic,readonly,copy)  NSArray <UIGestureRecognizer *> *gestureRecognizers NS_AVAILABLE_IOS(3_2);
 
//获取当前位置
- (CGPoint)locationInView:(nullable UIView *)view;
//获取上一个触摸点的位置
- (CGPoint)previousLocationInView:(nullable UIView *)view;
 
// Force of the touch, where 1.0 represents the force of an average touch
@property(nonatomic,readonly) CGFloat force NS_AVAILABLE_IOS(9_0);
// Maximum possible force with this input mechanism
@property(nonatomic,readonly) CGFloat maximumPossibleForce NS_AVAILABLE_IOS(9_0);
 
@end