温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

touchesEnded中区分触摸类型

发布时间:2020-04-03 16:25:58 来源:网络 阅读:538 作者:aprogram 栏目:开发技术

公司项目中需要为一个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);
    }
}


搞定,打完收工。。。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI