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

(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

你可能感兴趣的:(UI初级,经典例题,手指触摸事件)