热门IT资讯网

touchesEnded中区分触摸类型

发表于:2024-11-25 作者:热门IT资讯网编辑
编辑最后更新 2024年11月25日,公司项目中需要为一个view添加手势,短按则消失,长按就保存到相册,为了在touchesEnded中区分长按和短按开始了google和百度,百度中有人说可以通过以下方式来实现:- (void)touc

公司项目中需要为一个view添加手势,短按则消失,长按就保存到相册,为了在

touchesEnded中区分长按和短按开始了google和百度,百度中有人说可以通过以下方式来实现:

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{    UITouch *aTouch = [touches anyObject];    for(int i = 0; i < [aTouch.gestureRecognizers count] ;i ++){        UIGestureRecognizer *gesture = [aTouch.gestureRecognizers objectAtIndex:i];        if([gesture isKindOfClass:[UILongPressGestureRecognizer class]]){            //do what you want to do...        }    }}

经过验证发现aTouch.gestureRecognizers.count为0,根本无法判断是否长按,万般无奈下只好为view添加了UILongPressGestureRecognizer和UITapGestureRecognizer手势,功能倒是实现,可心里还是不舒服,觉得ios不应该犯如此低级错误,居然在touchesEnded里无法区分长按短按,心塞啊~

好吧,为了消除我心中的郁闷,继续研究,打印长按和短按的touch信息

短按:

 phase: Ended tap count: 1 window: ; layer = > view: > location in window: {198.66667175292969, 332} previous location in window: {197, 332.66665649414062} location in view: {122.000005086263, 115.33333333333337} previous location in view: {120.33333333333331, 115.999989827474}

长按:

 phase: Ended tap count: 0 window: ; layer = > view: > location in window: {184.66667175292969, 454.66665649414062} previous location in window: {188.33332824707031, 455.33334350585938} location in view: {108.000005086263, 237.999989827474} previous location in view: {111.66666158040363, 238.66667683919275}

突然发现tap count是不同的,再查苹果的文档,果然如此,于是就有了以下轻松愉快的代码:

-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{    UITouch *aTouch = [touches anyObject];    NSInteger tapCount = aTouch.tapCount;    if (1 == tapCount) { //短按        [self removeFromSuperview];    }    else if (0 == tapCount) { //长按        UIImage *p_w_picpath = [self captureView];        UIImageWriteToSavedPhotosAlbum(p_w_picpath, self, @selector(p_w_picpath:didFinishSavingWithError:contextInfo:), nil);    }}


搞定,打完收工。。。

0