1. 程式人生 > >IOS學習 觸控和手勢UITouch 單擊雙擊、移動檢視

IOS學習 觸控和手勢UITouch 單擊雙擊、移動檢視

@interface HomeViewController : UIViewController

{

    UIView *touchView;

    UITouch *touch;

    NSInteger *tapcount;

    CGPoint point;

    UIView *movieView;

}

@end

@implementation HomeViewController

- (void)viewDidLoad {

    [superviewDidLoad];

// Do any additional setup after loading the view.

touchView = [[UIViewalloc]initWithFrame:CGRectMake(0, 20, self.view.bounds.size.width, 500)];

touchView.backgroundColor = [UIColorcyanColor];

    [self.view addSubview:touchView];

//是否支援多點觸控,預設為NO

touchView.multipleTouchEnabled = YES ;

//是否開啟觸控事件,預設為開啟

touchView.userInteractionEnabled = YES;

movieView

= [[UIViewalloc]initWithFrame:CGRectMake(0, 0, 50, 50)];

movieView.backgroundColor = [UIColorredColor];

    [touchView addSubview:movieView];

}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

//    NSLog(@"touchesBegan");

    touch = [touches anyObject];  //獲取點選內容

tapcount = touch.tapCount;   //獲取短時間內點選的次數

NSLog(@"tapCount = %d",tapcount);

//設定單雙擊事件

    if (tapcount == 1) {

//延遲時間呼叫單擊事件

        [selfperformSelector:@selector(singleTap) withObject:nilafterDelay:0.5];

    }else if(tapcount == 2){

//取消單擊延遲事件

        [NSObjectcancelPreviousPerformRequestsWithTarget:selfselector:@selector(singleTap) object:nil];

        [self doubleTap];

    }

//獲取觸控點在檢視上的座標

point = [touchlocationInView:touchView];

NSLog(@"%@",NSStringFromCGPoint(point));//將座標轉換成字元列印

}

- (void)singleTap{

    NSLog(@"單擊");

}

- (void)doubleTap{

    NSLog(@"雙擊");

}

-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

//    NSLog(@"touchesMoved");

//重新獲取

    touch = [touches anyObject];

point = [touchlocationInView:touchView];

    CGRect frame = movieView.frame //獲取frame

    frame.origin = point //將移動游標的座標賦值給frame

movieView.frame = frame;  //重新賦值給檢視movieView

}

-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

//    NSLog(@"touchesEnded");    

}

-(void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

//    NSLog(@"touchesCancelled");

}