Rya*_*Dao 17 uigesturerecognizer ios
我正在开发一种游戏,通过长按对象本身来设置游戏对象的属性.属性的值由长按手势的持续时间确定.我正在使用UILongPressGestureRecognizer来实现这个目的,所以它是这样的:
[gameObjectView addGestureRecognizer:[[UILongPressGestureRecognizer alloc]
initWithTarget:self action:@selector(handle:)]];
Run Code Online (Sandbox Code Playgroud)
然后是处理函数
- (void)handle:(UILongPressGestureRecognizer)gesture {
if (gesture.state == UIGestureRecognizerStateEnded) {
// Get the duration of the gesture and calculate the value for the attribute
}
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,如何获得长按手势的持续时间?
Rup*_*ick 29
我很确定这个手势不会存储这些信息供您访问.您只能在其上设置名为minimumPressDuration的属性,该属性是识别手势之前的时间量.
使用ios 5(未经测试)的解决方法:
创建一个名为timer的NSTimer属性: @property (nonatomic, strong) NSTimer *timer;
一个柜台: @property (nonatomic, strong) int counter;
然后 @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];
}
}
Run Code Online (Sandbox Code Playgroud)
因此,当手势开始时,启动定时器,该定时器每秒触发增量方法,直到手势结束.在这种情况下,您需要将其设置minimumPressDuration为0,否则手势将不会立即开始.然后用计数器做你想做的事!
不需要计时器.你可以用这种方式实现它:
- (void)handleRecognizer:(UILongPressGestureRecognizer *)gesture
{
static NSTimeInterval pressStartTime = 0.0; //This an be moved out and be kept as a property
switch ([gesture state])
{
case UIGestureRecognizerStateBegan:
//Keeping start time...
pressStartTime = [NSDate timeIntervalSinceReferenceDate];
break; /* edit*/
case UIGestureRecognizerStateEnded:
{
//Calculating duration
NSTimeInterval duration = [NSDate timeIntervalSinceReferenceDate] - pressStartTime;
//Note that NSTimeInterval is a double value...
NSLog(@"Duration : %f",duration);
break;
}
default:
break;
}
}
Run Code Online (Sandbox Code Playgroud)
另外不要忘记设置手势识别的minimumPressDuration,以0在创建它,如果你想获得长按真正的持续时间:
myLongPressGestureRecognizer.minimumPressDuration = 0
到目前为止,面向对象的Cocoa Touch中最干净,最简单的解决方案似乎是UILongPressGesture的子类.这是一个用Swift编写的例子.
class MyLongPressGesture : UILongPressGestureRecognizer {
var startTime : NSDate?
}
func installGestureHandler() {
let longPress = MyLongPressGesture(target: self, action: "longPress:")
button.addGestureRecognizer(longPress)
}
@IBAction func longPress(gesture: MyLongPressGesture) {
if gesture.state == .Began {
gesture.startTime = NSDate()
}
else if gesture.state == .Ended {
let duration = NSDate().timeIntervalSinceDate(gesture.startTime!)
println("duration was \(duration) seconds")
}
}
Run Code Online (Sandbox Code Playgroud)
如果要包括第一次点击的时间,可以在计算持续时间时将其包括在内,方法是添加回手势.minimumPressDuration.鉴于在被触发的手势和被调用的.Start处理程序之间可能存在少量(微小的)时间,缺点是它可能不是微秒精确的.但对于绝大多数应用而言并不重要.
| 归档时间: |
|
| 查看次数: |
27522 次 |
| 最近记录: |