我正在创建一个程序,其中鸟类的图像连续从屏幕顶部掉落(就像“雨中的”鸟类一样)。为了使每只鸟都有一个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);

}

最佳答案

首先,从viewDidLoad类中删除moveObjectBirdUIImageView方法,然后在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);

}

关于iphone - xcode:将UIImageView子类与NSTimers一起使用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13589392/

10-14 21:01
查看更多