2012-11-03 97 views
1

我想简单地有一个循环,以便一个对象在底部不断移动屏幕。这是我的代码,它应该很容易理解。使对象在屏幕上移动iphone?

@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

+0

也,我有两个帐户已经几个月前,他们被禁止,因为我问的坏问题。我不确定你是否被允许在stackoverflow上拥有多个账户,所以如果你不被允许,我在这里被禁止,我不会再做账了。虽然我意识到这个网站是多么重要,我不会做任何不必要的问题。 –

+2

可能值得提供如何创建'ViewController',这可能是一个问题。 – WDUK

回答

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. 调用spawnRocketviewDidLoad可能不是最好的主意,它可能不会在调用spawnRocket时到达屏幕。尝试调用它viewWillAppearviewDidAppear(无论是最好的,你的情况)

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

    你不需要内withObject:提供self,你不接受内spawnRocket

任何参数
+0

是的,做了它 –

0

您不要将UIImageView添加到任何父视图。它只会生活在记忆中,但不会被显示。将它添加到您的视图控制器的视图创建后:

[self.view addSubview:rocket]; 
+0

啊,这是正确的,我忘了那部分thanx :) –

+0

哦,不,我只是试过,它仍然无效:( –

+0

是的,但我认为设置背景颜色将足以看到它 –