让一个物体在屏幕上移动iphone?

时间:2012-11-03 19:00:36

标签: iphone xcode animation uiimageview

我想简单地设置一个循环,以便对象在底部的屏幕上连续移动。这是我的代码,应该很容易理解。

@interface ViewController ()

@end

@implementation ViewController




    - (void)viewDidLoad
    {
        [super viewDidLoad];
        [self performSelector:@selector(spawnRocket) withObject:self afterDelay:2]; //delay before the object moves

    }

    -(void)spawnRocket{
        UIImageView *rocket=[[UIImageView alloc]initWithFrame:CGRectMake(-25, 528, 25, 40)]; //places imageview right off screen to the bottom left
        rocket.backgroundColor=[UIColor grayColor];

        [UIView animateWithDuration:5 animations:^(){rocket.frame=CGRectMake(345, 528, 25, 40);} completion:^(BOOL finished){if (finished)[self spawnRocket];}]; //this should hopefully make it so the object loops when it gets at the end of the screen


    }

    - (void)didReceiveMemoryWarning
    {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }

    @end

完成所有这些后,我点击运行,我看到的是我的iphone 6.0模拟器上的白色屏幕

PS。我正在运行xcode 4.5.1

2 个答案:

答案 0 :(得分:1)

一些事情:

  1. UIImageView *rocket=[[UIImageView alloc]initWithFrame:...

    您没有为图像视图指定图像,最好的方法是使用:

    UIImage* image = [UIImage imageNamed:@"image.png"];
    UIImageView *rocket = [[UIImageView alloc] initWithImage:image];
    rocket.frame = CGRectMake(-25, 528, 25, 40);
    
  2. (问题的根本原因)您没有将UIImageView添加到主视图中,因此未显示。在spawnRocket中,你应该这样做:

    [self.view addSubview:rocket];
    

    注意:因为您希望在循环中完成此操作,所以您必须确保内存管理正常。

    我不知道你完成移动后是否仍然希望火箭在屏幕上显示,但如果没有,请记住在完成后保留对UIImageViewremoveFromSuperview的引用(至防止内存泄漏)。

  3. spawnRocket中调用viewDidLoad可能不是最好的主意,但在调用spawnRocket时可能无法到达屏幕。尝试在viewWillAppearviewDidAppear中调用它(在您的情况下最好)

  4. [self performSelector:@selector(spawnRocket) withObject:self afterDelay:2];

    您无需在self内提供withObject:,也不接受spawnRocket

  5. 中的任何参数

答案 1 :(得分:0)

您不能将UIImageView添加到任何父视图中。它只会存在于内存中,但不会显示出来。创建后将其添加到视图控制器的视图中:

[self.view addSubview:rocket];
相关问题