用于持续触摸的iOS事件

时间:2014-02-06 23:49:57

标签: ios iphone objective-c uiview touch

我正在编写一个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)];
    }
}

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

3 个答案:

答案 0 :(得分:3)

您在搜索touchesMoved方法吗?有这样一种方法可以使用它。

<强>更新

Maddy的解决方案应该有效。

或者,您可能需要查看以下控件事件方法:

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

答案 1 :(得分:1)

根据您更新的问题,您需要在touchesBegan中设置重复计时器。每次计时器触发时,都会更新偏移量。使用touchesEndedtouchesCanceled方法取消计时器。

答案 2 :(得分:1)

感谢Maddy的提示。在接触有关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];
}