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

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

-(void)touchesEnded:(NSSet*)toucheswithEvent:(UIEvent*)event{UITouch*aTouch=[touchesanyObject];for(inti=0;i<[aTouch.gestureRecognizerscount];i++){UIGestureRecognizer*gesture=[aTouch.gestureRecognizersobjectAtIndex:i];if([gestureisKindOfClass:[UILongPressGestureRecognizerclass]]){//dowhatyouwanttodo...}}}

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

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

短按:

<UITouch:0x1703801a0>phase:Endedtapcount:1window:<UIWindow:0x156d467c0;frame=(00;414736);autoresize=W+H;gestureRecognizers=<NSArray:0x17024b280>;layer=<UIWindowLayer:0x170233aa0>>view:<UIView:0x156d83810;frame=(76.6667216.667;261303);layer=<CALayer:0x170234d40>>locationinwindow:{198.66667175292969,332}previouslocationinwindow:{197,332.66665649414062}locationinview:{122.000005086263,115.33333333333337}previouslocationinview:{120.33333333333331,115.999989827474}

长按:

<UITouch:0x17018f220>phase:Endedtapcount:0window:<UIWindow:0x14e661ee0;frame=(00;414736);autoresize=W+H;gestureRecognizers=<NSArray:0x17005eed0>;layer=<UIWindowLayer:0x17003e700>>view:<UIView:0x14e5a2cb0;frame=(76.6667216.667;261303);layer=<CALayer:0x1744329e0>>locationinwindow:{184.66667175292969,454.66665649414062}previouslocationinwindow:{188.33332824707031,455.33334350585938}locationinview:{108.000005086263,237.999989827474}previouslocationinview:{111.66666158040363,238.66667683919275}

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

-(void)touchesEnded:(NSSet*)toucheswithEvent:(UIEvent*)event{UITouch*aTouch=[touchesanyObject];NSIntegertapCount=aTouch.tapCount;if(1==tapCount){//短按[selfremoveFromSuperview];}elseif(0==tapCount){//长按UIImage*p_w_picpath=[selfcaptureView];UIImageWriteToSavedPhotosAlbum(p_w_picpath,self,@selector(p_w_picpath:didFinishSavingWithError:contextInfo:),nil);}}


搞定,打完收工。。。