我正在创建一个程序,其中一只鸟的图像从屏幕顶部不断下降(如“下雨”的鸟类)。为了获得每只鸟的NSTimer,我创建了一个UIImageView子类(称为“BirdUIImageView”)。但是,我不确定如何正确实现代码 - 在哪里放什么等等。
以下是我在ViewController.m中的代码:
#import "ViewController.h"
#import "BirdUIImageView.h"
@interface ViewController ()
@end
@implementation ViewController {
BirdUIImageView *_myImage;
}
- (void)viewDidLoad
{
//IMAGE CREATOR TIMER
createImagesTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(createImages) userInfo:nil repeats:YES];
}
//CREATES AN IMAGE
-(void) createImages {
srand(time(NULL));
int random_x_coordinate = rand() % 286;
CGRect myImageRect = CGRectMake(random_x_coordinate, 0.0f, 40.0f, 40.0f);
BirdUIImageView *myImage = [[BirdUIImageView alloc] initWithFrame:myImageRect];
[myImage setImage:[UIImage imageNamed:@"flake.png"]];
myImage.opaque = YES;
[self.view addSubview:myImage];
_myImage = myImage;
}
这是我在BirdUIImageView.m中的代码。我完全不知道该怎么做这个文件,但我做了一个尝试:
#import "BirdUIImageView.h"
@implementation BirdUIImageView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
- (void)viewDidLoad
{
//FALLING BIRDS TIMER
moveObjectTimer = [NSTimer scheduledTimerWithTimeInterval:0.001 target:self selector:@selector(moveObject) userInfo:nil repeats:YES];
}
//FALLING BIRDS MOVER
-(void) moveObject {
_myImage.center = CGPointMake(_myImage.center.x, _myImage.center.y +1);
}
答案 0 :(得分:3)
首先,从viewDidLoad
课程中删除moveObject
和BirdUIImageView
方法,然后在ViewController.m
课程中尝试以下代码。您可以使用计时器设置,以获得所需的效果:
在ViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
createImagesTimer = [NSTimer scheduledTimerWithTimeInterval:2.5
target:self
selector:@selector(createImages)
userInfo:nil
repeats:YES];
}
//CREATES AN IMAGE
-(void) createImages {
srand(time(NULL));
int random_x_coordinate = rand() % 286;
CGRect myImageRect = CGRectMake(random_x_coordinate, 0.0f, 40.0f, 40.0f);
BirdUIImageView *myImage = [[BirdUIImageView alloc] initWithFrame:myImageRect];
[myImage setImage:[UIImage imageNamed:@"flake.png"]];
myImage.opaque = YES;
[self.view addSubview:myImage];
_myImage = myImage;
[self move];
}
-(void)move {
//FALLING BIRDS TIMER
moveObjectTimer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(moveObject) userInfo:nil repeats:YES];
}
//FALLING BIRDS MOVER
-(void) moveObject {
_myImage.center = CGPointMake(_myImage.center.x, _myImage.center.y +1);
}