iOS:如何获得长按手势的持续时间? [英] iOS: How to get duration of long press gesture?

查看:1220
本文介绍了iOS:如何获得长按手势的持续时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一种游戏,其中通过长按对象本身来设置游戏对象的属性。属性的值由长按手势的持续时间确定。我正在使用UILongPressGestureRecognizer,所以它是这样的:

I'm working on a game in which an attribute of a game object is set by long pressing on the object itself. The value of the attribute is determined by the duration of the long press gesture. I'm using UILongPressGestureRecognizer for this purpose, so it's something like this:

[gameObjectView addGestureRecognizer:[[UILongPressGestureRecognizer alloc] 
                                       initWithTarget:self action:@selector(handle:)]];

然后处理函数

- (void)handle:(UILongPressGestureRecognizer)gesture {
  if (gesture.state == UIGestureRecognizerStateEnded) {
    // Get the duration of the gesture and calculate the value for the attribute
  }
}

如何获得长按的持续时间在这种情况下的手势?

How do I get the duration of the long press gesture in this case?

推荐答案

我很确定手势不会存储此信息供您访问。您只能在其上设置一个名为minimumPressDuration的属性,该属性是识别手势之前的时间。

I'm pretty sure the gesture doesn't store this information for you to access. You can only set a property on it called minimumPressDuration that is the amount of time before the gesture is recognised.

使用ios 5(未经测试)的解决方法:

Workaround with ios 5 (untested):

创建名为timer的NSTimer属性: @property(非原子,强)NSTimer *计时器;

Create an NSTimer property called timer: @property (nonatomic, strong) NSTimer *timer;

还有一个计数器: @property(非原子,强)int计数器;

然后 @synthesize

- (void)incrementCounter {
    self.counter++;
}

- (void)handle:(UILongPressGestureRecognizer)gesture {
    if (gesture.state == UIGestureRecognizerStateBegan) {
         self.counter = 0;
         self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(incrementCounter) userInfo:nil repeats:yes];
    }
    if (gesture.state == UIGestureRecognizerStateEnded) {
        [self.timer invalidate];
    }
}

因此,当手势开始时,启动一个启动计时器每秒增量方法,直到手势结束。在这种情况下,您需要将 minimumPressDuration 设置为0,否则手势将不会立即开始。然后用计数器做任何你想做的事情!

So when the gesture begins start a timer that fires the incrementation method every second until the gesture ends. In this case you'll want to set the minimumPressDuration to 0 otherwise the gesture won't start straight away. Then do whatever you want with counter!

这篇关于iOS:如何获得长按手势的持续时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆