拖动一个View移动的方法,简述UITouch

2016-04-03  本文已影响768人  rxdxxxx

UITouch

当用户用一根手指触摸屏幕时,会创建一个与手指相关联的UITouch对象

一根手指对应一个UITouch对象

属性

// 触摸产生时所处的窗口
@property(nullable,nonatomic,readonly,strong) UIWindow                        *window;

// 触摸产生时所处的视图
@property(nullable,nonatomic,readonly,strong) UIView                          *view;

// 记录了触摸事件产生或变化时的时间,单位是秒
@property(nonatomic,readonly) NSTimeInterval      timestamp;

// 当前触摸事件所处的状态
@property(nonatomic,readonly) UITouchPhase        phase;

// 短时间内点按屏幕的次数,可以根据tapCount判断单击、双击或更多的点击
@property(nonatomic,readonly) NSUInteger          tapCount;   // touch down within a certain point within a certain amount of time
@property(nonatomic,readonly) UITouchType         type NS_AVAILABLE_IOS(9_0);

// 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);



方法

    - (CGPoint)locationInView:(nullable UIView *)view;
- (CGPoint)previousLocationInView:(nullable UIView *)view;

例子

拖拽一个view移动

// 当手指在view上移动的时候
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSLog(@"%s",__func__);
    
    // 获取UITouch对象
    UITouch *touch = [touches anyObject];
    
    // 获取当前点
    CGPoint curP = [touch locationInView:self];
    
    // 获取上一个点
    CGPoint preP = [touch previousLocationInView:self];
    
    // 获取x轴偏移量
    CGFloat offsetX = curP.x - preP.x;
    
    // 获取y轴偏移量
    CGFloat offsetY = curP.y - preP.y;
    
    // 修改view的位置(frame,center,transform)
    // 每次移动需要和上一次做比较, 所有使用CGAffineTransformTranslate
    self.transform = CGAffineTransformTranslate(self.transform, offsetX, offsetY);
       
}

其他

如果你需要一个view监听多个手指触摸记得需要开启view的一个属性

@property(nonatomic,getter=isMultipleTouchEnabled) BOOL multipleTouchEnabled __TVOS_PROHIBITED;   // default is NO

上一篇 下一篇

猜你喜欢

热点阅读