2012-03-29 3 views
-1

Я искал по всему Интернету, не желая, чтобы этот проект работал с таймером, я получаю сбойное приложение каждый раз при использовании таймера.Добавление NSTimer к кнопке

Для тестирования и обучения я создаю небольшие простые приложения. Это кнопка, которая посылает ракету снизу экрана и исчезает с экрана, а также звуковой эффект ракеты.

Я хочу добавить таймер к кнопке, так что, когда кнопка удерживается, ракета запускается, перезагружается и запускается снова и снова, пока я не отпущу кнопку. Я думаю, что теперь моя единственная надежда - вставить код из моего .h & .m файлов, и, надеюсь, кто-то может сказать мне, что мне нужно делать, и где для этого проекта нужно добавить правильный код.

Большое вам спасибо за помощь, мы очень благодарны.

.Н FILE:

// MVViewController.h 
#import <UIKit/UIKit.h> 
#import <AVFoundation/AVFoundation.h> 

@interface MVViewController : UIViewController 

@property (strong, nonatomic) IBOutlet UIImageView *moveMe2; 

//New action to repeat launch (Touch Down) 
- (IBAction)rocketRepeat:(id)sender; 

//New action to stop launch (Touch Up Inside) 
- (IBAction)rocketStop:(id)sender; 

//This is the original launch button (Touch Down) 
- (IBAction)yourRocketButton:(id)sender; 

@end 

.М FILE

// MVViewController.m 

#import "MVViewController.h" 

@interface MVViewController() 

@end 

@implementation MVViewController { 
    AVAudioPlayer *audioPlayer; 
} 

@synthesize moveMe2; 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
} 

- (void)viewDidUnload 
{ 
    [self setMoveMe2:nil]; 
    [super viewDidUnload]; 
} 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{ 
    return ((interfaceOrientation == UIInterfaceOrientationPortrait) || (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)); 
} 

- (IBAction)rocketRepeat:(id)sender 
//Getting error "Use of undeclared identifier 'yourRocketButton' 
{ 
    [yourRocketButton addTarget:self action:@selector(rocketRepeat:) forControlEvents:UIControlEventTouchDown]; 
} 

- (IBAction)rocketStop:(id)sender 
//Getting error "Use of undeclared identifier 'yourRocketButton' 
{ 
    [yourRocketButton addTarget:self action:@selector(rocketStop:) forControlEvents:UIControlEventTouchUpInside]; 
} 

- (IBAction)yourRocketButton:(id)sender { 
    moveMe2.center = CGPointMake(100.0f, 408.0f); 
    [UIView animateWithDuration:2.0 animations:^{moveMe2.center = CGPointMake(100, -55);}]; 
} 

@end 

@@@@@@@@

EDIT * Это то, что, наконец, работал *

// RKViewController.m 

#import "RKViewController.h" 

@interface RKViewController() 

@end 

@implementation RKViewController 
@synthesize RocketMove; 
@synthesize Launch; 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
} 

- (void)viewDidUnload 
{ 
    [self setRocketMove:nil]; 
    [self setLaunch:nil]; 
    [super viewDidUnload]; 
} 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{ 
    return ((interfaceOrientation == UIInterfaceOrientationPortrait) || (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)); 
} 

- (IBAction)rocketRepeat:(id)sender { 
    [self performSelector:@selector(rocketRepeat:) withObject:self afterDelay:1.0]; 
    RocketMove.center = CGPointMake(100.0f, 408.0f); 
    [UIView animateWithDuration:1.0 animations:^{RocketMove.center = CGPointMake(100, -55);}]; 
} 

- (IBAction)rocketStop:(id)sender { 
    [NSObject cancelPreviousPerformRequestsWithTarget:self]; 
} 
@end 

// RKViewController.h 

#import <UIKit/UIKit.h> 

@interface RKViewController : UIViewController 

@property (strong, nonatomic) IBOutlet UIImageView *RocketMove; 
@property (strong, nonatomic) IBOutlet UIButton *Launch; 

- (IBAction)rocketRepeat:(id)sender; 
- (IBAction)rocketStop:(id)sender; 
@end 

ответ

1

Вы должны использовать UIControlEvent для этой цели.

1. Для каждой цели вам нужно два отдельных IBAction s, например один для удержания кнопки, один после отпускания кнопки.

2. Для удержания кнопки необходимо использовать UIControlEventTouchDown. Так есть rocketRepeat действия, где вы продолжаете призывающее действие ракеты с помощью NSTimer с регулярными интервалами и использованием:

[yourRocketButton addTarget:self action:@selector(rocketRepeat:) forControlEvents:UIControlEventTouchDown]; 

3. Затем использовать другое действие с UIControlEventTouchUpInside, где вы будете недействительной NSTimer около того ракетных остановок. Позвони, что действие rocketStop или что-то и использовать:

[yourRocketButton addTarget:self action:@selector(rocketStop:) forControlEvents:UIControlEventTouchUpInside]; 

--- EDIT ---

Действие 1:

- (IBAction)rocketRepeat:(id)sender 
{ 
    //code for starting rocker, timer action 
} 

Действие 2:

- (IBAction)rocketStop:(id)sender 
{ 
    //Code for stopping rocket 
} 

yourButton не является действием, его UIButton. Надеюсь, вы создали кнопку в IB, перетащили и сбросили кнопку.И в viewDidLoad вы пишете эти 2 строки кода:

Вместо yourButton вы пишете имя кнопки, которую вы перетащили из IB. Надеюсь, вы знаете, как добавить кнопку из конструктора интерфейса и подключить его.

- (void)viewDidLoad 
{ 
    [yourRocketButton addTarget:self action:@selector(rocketRepeat:) forControlEvents:UIControlEventTouchDown]; //For touch down button action 
    [yourRocketButton addTarget:self action:@selector(rocketStop:) forControlEvents:UIControlEventTouchUpInside]; //When button is let go. 

    [super viewDidLoad]; 


    // Do any additional setup after loading the view, typically from a nib. 
} 
+0

Я написал код с указанием названий действий и предоставил правильные подключения. Я получаю сообщение об ошибке в каждом IBAction в файле .M. Я переименовал действие анимации «yourRocketButton». Ошибки говорят «использование необъявленного идентификатора« yourRocketButton »(я уверен, что я просто неправильно вас понял или что-то в этом роде) – sdlabs

+0

@sdlabs' yourRocketButton' - просто имя примера, вы должны заменить его именем своей кнопки, кнопкой, которую вы используете нажимать на. – iNoob

+0

Я подключил IBAction для анимации в соответствии с вашим примером. Я что-то упускаю, когда дело доходит до того, что на самом деле дает кнопку имя? – sdlabs

1

Если вы хотите, чтобы ракеты autolaunched после нажатия на кнопку, вы должны добавить следующий код в rocketLaunch: метод. Если вы хотите, чтобы они начали появляться с самого начала, вызовите это из метода viewDidLoad.

- (void)launchRocketsTimer 
{ 
    [self.timer invalidate]; //you have to create a NSTimer property to your view controller 
    self.timer = [NSTimer scheduledTimerWithTimeInterval:2.5 target:self selector:@selector(scheduledRocketLaunch:) userInfo:nil repeats:YES]; 
} 

- (void)scheduledRocketLaunch:(NSTimer *)t 
{ 
    moveme2.center = _bottom_point_; //set it where you would like it to start 
    [UIView animateWithDuration:2.0 animations:^{moveMe2.center = CGPointMake(100, -55);}]; 
} 

Не забудьте освободить свой таймер в dealloc.

О, и еще одна вещь: У вас есть утечка памяти на вашем rocketsound: метод при распределении вашего AVAudioPlayer. Вы можете заменить код на этот:

- (IBAction)rocketsound:(id)sender 
{ 
    NSURL *url = [NSURL fileURLWithPath: [NSString stringWithFormat:@"%@/rocketlaunch.mp3", [[NSBundle mainBundle] resourcePath]]]; 

    NSError *error; 
    if (self.audioPlayer == nil) 
    { 
     self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error] autorelease]; //Note the use of setter property and the autorelease. (you could use your own code because the if will prevent the leak in this case). 
    } 

    audioPlayer.numberOfLoops = 0; 

    if (audioPlayer == nil) 
     NSLog(@"%@", [error description]); 
    else 
     [audioPlayer play]; 
} 
Смежные вопросы