您好,登錄后才能下訂單哦!
公司項目中需要為一個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); } }
搞定,打完收工。。。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。