简体   繁体   中英

Creating a Button to Add Images in Swift

I am making a game and I need to have a button that when pressed will add an image (ImageView) to the screen, and when pressed again will add another image in a different position. This button has to be able to be pressed and add images until the game ends. My issue, however, is that I am relatively new to programing and I don't know how to make such a botton, or if such a button is even possible. If you need more info just tell me and I will provide all that I can. Thanks if advance for any help I can get!

Here is code to create UIImageView Programatically, paste the code on button press event. It will create new UIImageView with the size and co-ordinate you provide

  UIImageView *imageX =[[UIImageView alloc]initWithFrame:CGRectMake(50,50,120,120)];
  imageX.image=[UIImage imageNamed:@"sample.png"];
 [self.view addSubview:imageX];

change x,y,width,height of UIImageView as per your need.

Swift:

Declare UIImageView with image name,

 let imageName = "sample.png"
 let image = UIImage(named: imageName)
 let imageX = UIImageView(image: image!)

Now set position to UIImageView

 imageX.frame = CGRect(x: 50, y: 50, width: 120, height: 120)
 view.addSubview(imageX)

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