手指触摸事件【小球跟随手指】

(1)设置根视图控制器

(2)将TouchView添加到RootViewController

(3)TouchView.h将_view设为全局变量

TouchView.m

#import "TouchView.h"

@implementation TouchView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
//        开启多点触摸
        self.multipleTouchEnabled = YES;
        
        //开启相应时间,默认是yes,除了imageView
        self.userInteractionEnabled = YES;
        
        _view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 15, 15)];
        _view.backgroundColor = [UIColor redColor];
        [self addSubview:_view];
        
    }
    return self;
}

//开始触摸,手指触摸到屏幕的时候调用的方法
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    //点击的手指的个数
    NSInteger touchCount = touches.count;
//    NSLog(@"touchCount:%d",touchCount);
    
    //取出点击的touch
    UITouch *touch = [touches anyObject];
    //取得他的点击次数
    NSInteger count = [touch tapCount];//touch.tapCount
//    NSLog(@"count:%d",count);
    
    if (count == 1) {
        //单击的时候调用的方法
//        [self signalTap];
        //延迟调用单击的方法
        [self performSelector:@selector(signalTap) withObject:nil afterDelay:.5];
    }else if (count == 2) {
        //双击的时候调用的方法
//        [self doubleTap];
        //取消单击的方法
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(signalTap) object:nil];
        [self doubleTap];
    }
    
    //获取点击的所在window
//    UIWindow *window = touch.window;
//    NSLog(@"window:%@",window);
    //获取点击所在的视图
//    UIView *view = touch.view;
//    NSLog(@"view:%@",view);
  
    //取得点击的坐标
    CGPoint point = [touch locationInView:self];
//    _view.frame.origin = point;   不可以
    CGRect frame = _view.frame;
    frame.origin = point;
    _view.frame = frame;
    
}

//单击响应的事件
- (void)signalTap {

    NSLog(@"单击");
    
}

- (void)doubleTap {
 
    NSLog(@"双击");
}

//手指在屏幕上移动的时候调用的方法,如果手指在屏幕上移动的时候,这个方法会不停的调用
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

    
    UITouch *touch = [touches anyObject];
    //取得点击的坐标
    CGPoint point = [touch locationInView:self];
    //取得前一次的坐标
//    [touch previousLocationInView:<#(UIView *)#>]
    
    CGRect frame = _view.frame;
    frame.origin = point;
    _view.frame = frame;
    
}

触摸结束的时候调用的方法
//- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
//    NSLog(@"touchesEnded");
//}
//
触摸取消的时候调用的方法
//- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
//
//
//    NSLog(@"touchesCancelled");
//
//}

//手机开始摇动的时候调用的方法
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {


}

//- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
//- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event

@end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值