【问题标题】:Only allowing a single touchesMoved method triggered per period of time?只允许每个时间段触发一个 touchesMoved 方法?
【发布时间】:2013-06-15 13:17:32
【问题描述】:

我正在使用带有坐标系的touchesMoved 来检测和响应屏幕某些区域内的用户触摸。例如,如果我有一个虚拟键盘并且用户在按键上滑动,它会读取坐标并做出响应:

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch * touch = [[event allTouches] anyObject];
    CGPoint point = [touch locationInView:touch.view];
    if(point.y < 333 && point.y > 166 && point.x < 90 && point.x > 20)
    {
       //do something
    }
}

...但是问题是,如果用户慢慢拖过按键,或者按键之间的边界,该方法会连续触发多次,弹奏钢琴键的声音会断断续续。

如何防止这种口吃?我认为在每个连续的 if 语句触发之间设置 0.25 秒的最小延迟会有所帮助。此外,这种延迟仅适用于特定的 if 语句——我希望用户能够快速拖动键并尽可能快地触发不同键的 if 语句。

有人知道如何编写这样的代码吗?

【问题讨论】:

    标签: ios objective-c xcode touchesmoved


    【解决方案1】:

    试试这个:

    BOOL _justPressed; // Declare this in your @interface
    
    ...
    
    - (void)unsetJustPressed {
        _justPressed = NO;
    }
    

    那么,在你的touchesMoved

    - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
    {
        if (_justPressed) {
            // A key was just pressed, so do nothing.
            return;
        }
        else {
            _justPressed = YES;
    
            // Do stuff here
    
            [self performSelector:@selector(unsetJustPressed)
                       withObject:nil
                       afterDelay:0.25];
        }
    }
    

    这样,您将变量_justPressed 设置为YES,每个touchesMoved:withEvent: 被调用(或在其中的特定条件内,取决于您想要做什么),然后您使用performSelector:withObject:afterDelay: 设置@ 987654328@经过一定时间后变为NO,所以你可以在调用touchesMoved:时检查_justPressed是否为YES,以确定最近是否被调用。

    请记住,您不必从上面示例中的方法返回,您可以简单地使用_justPressed 来检查您是否应该播放声音,但仍然执行您的其他操作。这个例子只是为了让你知道该怎么做。

    【讨论】:

    • 非常感谢您的详细回答,它确实帮助解决了我的问题!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-01
    • 1970-01-01
    • 2015-04-15
    • 2012-06-02
    • 2011-08-28
    相关资源
    最近更新 更多