【问题标题】:Issues using touchesBegins使用 touchesBegins 的问题
【发布时间】:2013-09-13 21:50:34
【问题描述】:

我有一个按钮。我想在初次触摸时更改图像。如果触摸小于 1 秒,我希望它做 X。如果触摸长于 1 秒,我希望它做 Y。

我无法弄清楚如何处理这个问题。 UIButton 已经被证明很麻烦,所以我想我可以用 UIGestureRecognizerstouchesBegin: 来完成它

最初的想法是有一个UITapGestureRecognizer 来检测只是快速点击执行 X,并使用 UILongTapGestureRecognizer 处理更长的按下来执行 Y。

问题是UITapGestureRecognizer 没有标记UIGestureRecognizerStateBegan,它只会发送UIGestureRecognizerStateEnd 的通知。

所以我决定尝试结合使用覆盖touchesBegin:touchesEnd: 方法并使用UILongPressGestureRecognizer

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    // change image
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    // do X
    // change image to original image
}

-(IBAction)longPressDetected:(UILongPressGestureRecognizer *)recognizer {
    DLog(@"fired");

    if (recognizer.state == UIGestureRecognizerStateBegan) {
        // Do y
        // change image to original image
    }
    else if (recognizer.state == UIGestureRecognizerStateCancelled) {

    }
    else if (recognizer.state == UIGestureRecognizerStateEnded) {

    }
}

如果UILongPressGestureRecognzier 触发,它会取消初始touchesBegan:(不会触发touchesEnded: 方法)。

但我遇到了touchesBegin: 方法启动缓慢的问题。被触发的方法有 0.5 秒的延迟。让我感到困惑的是,如果我将UILongPressGestureRecognizerlongTap.minimumPressDuration = 0 一起使用,它会立即触发。

这是在我需要的程序中。在虚拟区域中使用它,touchesBegins: 也会立即触发。

什么可能导致它在程序中滞后?

有没有不同的方法可以获得想要的效果?

【问题讨论】:

    标签: ios objective-c uigesturerecognizer touchesbegan


    【解决方案1】:

    也许您可以使用计时器和长按手势识别器

    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(didRecognizeLongPressGesture:)];
    longPress.minimumPressDuration = 0;
    [self.button addGestureRecognizer:longPress];
    

    ...

    - (void)didRecognizeLongPressGesture:(UILongPressGestureRecognizer*)gesture
    {
        static NSTimer *timer = nil;
    
        if (gesture.state == UIGestureRecognizerStateBegan)
        {
            timer = [NSTimer scheduledTimerWithTimeInterval:1.1 target:self selector:@selector(changeImage:) userInfo:nil repeats:NO];
            //change the image here
        }
        else if ( gesture.state == UIGestureRecognizerStateEnded)
        {
            if ([timer isValid])
            {
                //the user has pressed the button less than a second
                [timer invalidate];
                timer = nil;
            }
    
        }
    
    }
    
    - (void)changeImage:(NSTimer*)timer
    {
        [timer invalidate];
        timer = nil;
    
        //change to the other image here
    }
    

    【讨论】:

    • 好的,这行得通。我删除了touchesBegins: 代码,长按立即响应,计时器工作正常。仍然不确定为什么touchesBegins: 方法如此缓慢,但手势是响应式的(我偷偷怀疑这与我使用NSLayConstraints 有关,但这是另一天弄清楚的任务)。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    • 2013-07-24
    • 2010-09-27
    • 2011-08-28
    • 2011-05-18
    相关资源
    最近更新 更多