2012-11-03 99 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

是的,但我認爲設置背景顏色將足以看到它 –