简体   繁体   中英

make an object move across the screen iphone?

I want to simply have a loop so that an object continuously moves across the screen at the bottom. Here is my code it should be pretty easy to understand.

@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

After doing all this i click run and all i see is a white screen on my iphone 6.0 simulator

ps. im running xcode 4.5.1

A few things:

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

    You're not assigning an image to the image view, the best way to do this is to use:

     UIImage* image = [UIImage imageNamed:@"image.png"]; UIImageView *rocket = [[UIImageView alloc] initWithImage:image]; rocket.frame = CGRectMake(-25, 528, 25, 40); 
  2. (The root cause of your problem) You are not adding your UIImageView to your main view, hence it's not being displayed. In spawnRocket , you should do:

     [self.view addSubview:rocket]; 

    Note: Because you want this to be done in a loop, you're gonna have to make sure your memory management is in order.

    I don't know whether you still want the rocket on screen after it's finished moving, but if not, remember to keep a reference to the UIImageView and removeFromSuperview when you're done (to prevent memory leaks).

  3. Calling spawnRocket in viewDidLoad is probably not the best idea, it may not reach the screen yet when spawnRocket is called. Try calling it in viewWillAppear or viewDidAppear (whatever is best in your case)

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

    You don't need to provide self within withObject: , you're not accepting any parameters within spawnRocket

You don't add the UIImageView to any parent view. It will just live in memory, but not be displayed. Add it to your view controller's view after creating it:

[self.view addSubview:rocket];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM