Help Creating a UIImageView

Discussion in 'iOS Programming' started by xcodeNewbie, Jul 11, 2011.

  1. macrumors member

    Joined:
    Jul 1, 2011
    #1
    I'm making a game in which the user controls a ship and has to shoot at other ships that fly by. When the user presses the button that says "shoot", the method "shoot" gets called, creating a UIImageView for the shot.
    Code:
    -(IBAction)shoot {
        UIImageView *shot = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"shot.jpg"]];
        [shot setBounds:CGRectMake(0, 0, 30, 30)];
    }
    I set the image to the top right corner of the screen for testing purposes. However, when I run the program and press "shoot", nothing happens. What am I doing wrong?
     
  2. Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #2
    You have not added the view as a subview of an existing visible view. So it is never drawn as it is not part of the on-screen view hierarchy.
     
  3. macrumors 65816

    pulsewidth947

    Joined:
    Jan 25, 2005
    Location:
    squarefrog.co.uk
    #3
    Code:
    -(IBAction)shoot {
        UIImageView *shot = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"shot.jpg"]];
        [shot setBounds:CGRectMake(0, 0, 30, 30)];
        [window addSubview:shot]; // syntax may be wrong there.. but along the right lines
        [shot release] // dont forget - if you alloc, you are responsible for releasing.
    }

    Also - if you haven't already seen it, start lurking on stack overflow.
     
  4. thread starter macrumors member

    Joined:
    Jul 1, 2011
    #4
    Another UIImageView question

    This is sort of an add on to a previous question...I create a UIImageView programmatically in the code below.
    Code:
    -(IBAction)shoot {
        UIImageView *shot = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"shot.jpg"]];
        [shot setBounds:CGRectMake(ship.center.x-15,ship.center.y-15,25,25)];
        [superView addSubview:shot];
        [shot release];    
    }  
    I'm trying to make it so the shot appears right above my ship, so it appears the ship is shooting. However, no matter how I change the CGRetMake, the shot will always appear in the upper left part of the screen. I even once set the starting coordinates to 99999999999 just to see what would happen. It still appeared in the top left corner of the screen.
     
  5. Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #5
    Read, and understand, the View Programming Guide. In particular pay attention to the difference between a views frame and it's bounds.
     

Share This Page