如何在touchesBegan和touchesEnded中实现Touch Up Inside

3

我想知道有没有人知道如何在touchesBegantouchesEnded方法中实现“touch up inside”响应,当用户按下然后松开手指时。我知道可以使用UITapGestureRecognizer来完成这个功能,但实际上我想让它只在快速轻触时起作用(如果您长时间按住您的手指,然后松开,它仍然会执行)。有人知道如何实现吗?

6个回答

4

使用 UILongPressGestureRecognizer 实际上是模拟所有 UIButton 的功能(touchUpInsidetouchUpOutsidetouchDown等)的更好解决方案:

- (void) longPress:(UILongPressGestureRecognizer *)longPressGestureRecognizer
{
    if (longPressGestureRecognizer.state == UIGestureRecognizerStateBegan || longPressGestureRecognizer.state == UIGestureRecognizerStateChanged)
    {

        CGPoint touchedPoint = [longPressGestureRecognizer locationInView: self];

        if (CGRectContainsPoint(self.bounds, touchedPoint))
        {
            [self addHighlights];
        }
        else
        {
            [self removeHighlights];
        }
    }
    else if (longPressGestureRecognizer.state == UIGestureRecognizerStateEnded)
    {
        if (self.highlightView.superview)
        {
            [self removeHighlights];
        }

        CGPoint touchedPoint = [longPressGestureRecognizer locationInView: self];

        if (CGRectContainsPoint(self.bounds, touchedPoint))
        {
            if ([self.delegate respondsToSelector:@selector(buttonViewDidTouchUpInside:)])
            {
                [self.delegate buttonViewDidTouchUpInside:self];
            }
        }
    }
}

3

我不确定这个属性是什么时候添加的,但是isTouchInside属性对于任何派生自UIControl的对象(例如UIButton)都非常有用。

override func endTracking(_ touch: UITouch?, with event: UIEvent?) {
    super.endTracking(touch, with: event)
    if isTouchInside {
        // Do the thing you want to do
    }
}

这里是苹果官方文档的链接:Apple official docs

2
我通过在touchesBegan中设置一个定时器来实现这一点。如果当调用touchesEnded时,该定时器仍在运行,则执行您想要的任何代码。这会产生touchUpInside的效果。
  -(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
        NSTimer *tapTimer = [[NSTimer scheduledTimerWithTimeInterval:.15 invocation:nil repeats:NO] retain];
        self.tapTimer = tapTimer;
        [tapTimer release];
    }

    -(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
    {
        if ([self.tapTimer isValid])
        {

        }
    }

这真的很聪明,易于理解。 - Chen Li Yong

2

您可以通过创建一个UIView子类并在其中实现touchesBegan和touchesEnded来实现。

但是,您也可以使用UILongPressGestureRecognizer来实现相同的结果。


0
你可以创建一些BOOL变量,然后在-touchesBegan中检查哪个视图或其他需要被触摸,并将此BOOL变量设置为YES。之后,在-touchesEnded中检查此变量是否为YES,并且您需要被触摸的视图或其他内容将成为您的-touchUpInside。当然,在此之后将BOOL变量设置为NO

0
你可以添加一个 UTapGestureRecognizer 和一个 UILongPressGestureRecognizer,并使用 [tap requiresGestureRecognizerToFail:longPress]; 添加依赖关系(其中 tap 和 long press 是已添加的识别器对象)。
这样,如果长按被触发,则不会检测到轻击。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接