繁体   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