簡體   English   中英

使對象在iPhone屏幕上移動?

[英]make an object move across the screen 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

一些東西:

  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]; 

    注意:因為您希望循環執行此操作,所以必須確保內存管理正常。

    我不知道火箭完成移動后是否仍要在屏幕上顯示火箭,但是如果不希望,請記住在完成后保留對UIImageView的引用和removeFromSuperview (以防止內存泄漏)。

  3. 調用spawnRocketviewDidLoad可能不是最好的主意,它可能無法到達屏幕但當spawnRocket被調用。 嘗試在viewWillAppearviewDidAppear調用它(以您的情況viewDidAppear

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

    您不需要在withObject:提供self也不需要在spawnRocket接受任何參數

您不會將UIImageView添加到任何父視圖。 它只會存在於內存中,而不會顯示。 創建后將其添加到視圖控制器的視圖中:

[self.view addSubview:rocket];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM