为什么计时器不会被取消?

时间:2016-02-07 06:58:37

标签: ios objective-c xcode cocoa-touch

我正在开发一个项目,要求用户点击屏幕停止和对象。我需要在点击屏幕后使ShakeTimer无效,但每当我运行应用程序时它都不会停止计时器。我已经测试了触摸开始部分是通过命令它来隐藏图像,当我点击并且已经工作但我不能使计时器无效。 AAAAH。为什么。代码如下。

#import "Game.h"

@interface Game ()

@end


@implementation Game

-(IBAction)Play:(id)sender{

   ShakeTimer = [NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:@selector(Shake) userInfo:nil repeats:NO];

     Play.hidden = YES;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    [ShakeTimer invalidate];
}

-(void)Shake{
    CABasicAnimation *shake = [CABasicAnimation animationWithKeyPath:@"position"];
    [shake setDuration:1];
    [shake setRepeatCount:INFINITY];
    [shake setAutoreverses:YES];
    [shake setFromValue:[NSValue valueWithCGPoint:
                         CGPointMake(Piece.center.x - 5,Piece.center.y)]];
    [shake setToValue:[NSValue valueWithCGPoint:
                       CGPointMake(Piece.center.x + 300, Piece.center.y)]];
    [Piece.layer addAnimation:shake forKey:@"position"];

}
- (void)viewDidLoad{
    Leave.hidden = YES;}

-(void)GameOver{
    Leave.hidden = NO;    
}

@end

1 个答案:

答案 0 :(得分:0)

我认为不是关于计时器停止与否,而是关于动画。

您的计时器仅被调用一次(如下repeats:NO所示):

ShakeTimer = [NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:@selector(Shake) userInfo:nil repeats:NO];

但动画似乎无限重复:

[shake setRepeatCount:INFINITY];

解决方案:

如果要在用户触摸视图时停止动画,则需要删除动画:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
  [Piece.layer removeAnimationForKey:@"position"];
  ...
}

编辑:

如果您想在下次用户触摸视图时再次启动动画:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
  if (self.layer animationForKey:@"position") {
    [ShakeTimer invalidate];
    [Piece.layer removeAnimationForKey:@"position"];
  } else {
    [self Play:nil];
    // or just 
    // ShakeTimer = [NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:@selector(Shake) userInfo:nil repeats:NO];
  }
  ...
}

实际上,我认为你甚至不需要计时器来处理它:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
  if (self.layer animationForKey:@"position") {
    [Piece.layer removeAnimationForKey:@"position"];
  } else {
    [self Shake];
  }
  ...
}