PDA

View Full Version : Help Creating a UIImageView




xcodeNewbie
Jul 11, 2011, 11:03 AM
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.
-(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?



robbieduncan
Jul 11, 2011, 11:07 AM
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.

pulsewidth947
Jul 11, 2011, 11:17 AM
-(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 (http://stackoverflow.com/).

xcodeNewbie
Jul 11, 2011, 11:25 AM
This is sort of an add on to a previous question...I create a UIImageView programmatically in the code below.
-(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.

robbieduncan
Jul 11, 2011, 11:33 AM
Read, and understand, the View Programming Guide (http://developer.apple.com/library/ios/#documentation/WindowsViews/Conceptual/ViewPG_iPhoneOS/Introduction/Introduction.html#//apple_ref/doc/uid/TP40009503). In particular pay attention to the difference between a views frame and it's bounds.