公司项目中需要为一个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信息
短按:
<UITouch: 0x1703801a0> phase: Ended tap count: 1 window: <UIWindow: 0x156d467c0; frame = (0 0; 414 736); autoresize = W+H; gestureRecognizers = <NSArray: 0x17024b280>; layer = <UIWindowLayer: 0x170233aa0>> view: <UIView: 0x156d83810; frame = (76.6667 216.667; 261 303); layer = <CALayer: 0x170234d40>> 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}
长按:
<UITouch: 0x17018f220> phase: Ended tap count: 0 window: <UIWindow: 0x14e661ee0; frame = (0 0; 414 736); autoresize = W+H; gestureRecognizers = <NSArray: 0x17005eed0>; layer = <UIWindowLayer: 0x17003e700>> view: <UIView: 0x14e5a2cb0; frame = (76.6667 216.667; 261 303); layer = <CALayer: 0x1744329e0>> 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);
}
}
搞定,打完收工。。。
转载于:https://blog.51cto.com/aprogram/1693094