Я искал по всему Интернету, не желая, чтобы этот проект работал с таймером, я получаю сбойное приложение каждый раз при использовании таймера.Добавление 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
Я написал код с указанием названий действий и предоставил правильные подключения. Я получаю сообщение об ошибке в каждом IBAction в файле .M. Я переименовал действие анимации «yourRocketButton». Ошибки говорят «использование необъявленного идентификатора« yourRocketButton »(я уверен, что я просто неправильно вас понял или что-то в этом роде) – sdlabs
@sdlabs' yourRocketButton' - просто имя примера, вы должны заменить его именем своей кнопки, кнопкой, которую вы используете нажимать на. – iNoob
Я подключил IBAction для анимации в соответствии с вашим примером. Я что-то упускаю, когда дело доходит до того, что на самом деле дает кнопку имя? – sdlabs