【问题标题】:iOS event for continuous touch用于持续触摸的 iOS 事件
【发布时间】:2014-02-06 23:49:56
【问题描述】:

我正在编写一个 iOS 应用程序,但我似乎无法弄清楚如何进行连续触摸事件。我尝试使用“touchesBegan”和“touchesEnd”功能,但它们不适用于连续触摸。

所以基本上我现在的情况如下:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];

    UITouch *touch = [touches anyObject];
    if([touch view] == [self viewWithTag:kTag])
    {
        CGFloat yOffset = contentView.contentOffset.y;
        yOffset ++;
        [contentView setContentOffset:CGPointMake(0, yOffset)];
    }
}

但是,只要我的手指触摸给定的视图,我希望内容偏移继续无限期地移动。现在它在一次迭代后停止。

【问题讨论】:

  • 您在寻找什么?如果您收到 touchesBegan,那么它会一直持续到您收到 touchesEnded。

标签: ios iphone objective-c uiview touch


【解决方案1】:

您在寻找touchesMoved 方法吗?有这样的方法可以用。

更新

Maddy 的解决方案应该适用于触摸。

或者,您可能想看看以下控制事件方法:

- (BOOL)continueTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event

【讨论】:

  • OP 不想要 touchesMoved 方法。这个想法是用户只需将手指放在屏幕上,当手指保持触摸时视图会移动。无需移动手指。
  • 谢谢麦迪。我已经同意我的回答听起来更像是一种评论,本质上是试图了解需求。我只有 1 个声誉,因此无法发表评论。话虽如此,我们可以在长按手势识别器中指定一个持续时间并使用它。更新了我的答案。
  • 长按手势也不起作用。这只在达到长按持续时间后发送一个事件,然后在手指移动时发送一个事件,然后在手指抬起时发送一个事件。 OP 想要在手指放在一个位置的整个过程中发生一组事件。
【解决方案2】:

根据您更新的问题,您似乎需要在touchesBegan 中设置一个重复计时器。每次计时器触发时,更新偏移量。在touchesEndedtouchesCanceled 方法中取消定时器。

【讨论】:

  • 我以前从未听说过 iOS 中的重复计时器。你能详细说明吗?我将如何实施?
  • 查看NSTimer 的文档。创建计时器时有设置重复的参数。
【解决方案3】:

感谢麦迪的提示。在处理有关 NSTimer 的信息时,我得到了一个重复的动作。

我确实让它在每次点击屏幕时执行一个操作:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[rocket.physicsBody applyForce:CGVectorMake(0,200)];
}

但这只会在每次点击时触发。我希望它在触摸屏幕时继续施加力。

在类中添加一个计时器:

@interface TPMyScene ()
@property (nonatomic, retain, readwrite) NSTimer * touchTimer;
@end

将我的操作移至方法:

-(void)boost {
    NSLog(@"Boosting");
    [rocket.physicsBody applyForce:CGVectorMake(0,200)];
}

在 touchesBegan 处触发计时器:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    // First we need to trigger a boost in case the screen was just touched.
    [rocket boost];

    //set a timer to keep boosting if the touch continues.  
    //Also check there isn't already a timer running for this.
    if (!self.touchTimer.isValid) {
        self.touchTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:rocket selector:@selector(boost) userInfo:nil repeats:YES];
    }
}

在触摸结束时取消计时器结束或取消:

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.touchTimer invalidate];
}

-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.touchTimer invalidate];
}

【讨论】:

  • 我的第一次 touchesBegan 仅使用计时器在我开始测试后有两个错误... 1. 计时器仅在 0.1 秒后触发,因此在运行之前取消了小于该时间的触摸/点击. 2. 多点触控:第二次触控会创建一个新的计时器并失去与原始计时器的链接。无效只会停止新的,而旧的会永远发射!
猜你喜欢
  • 2011-05-16
  • 1970-01-01
  • 1970-01-01
  • 2021-10-27
  • 1970-01-01
  • 2013-04-01
  • 1970-01-01
  • 2015-02-06
  • 2013-04-16
相关资源
最近更新 更多