Search code examples
iosswiftuibuttonuiimageviewuiimage

Is there a better way to change an Image in an ImageView by clicking a button?


Currently I am changing an image view by doing the following:

@IBOutlet var bgImage: UIImageView!

creating a UIimage view connected in storyboard and

var counter = 0
    @IBAction func ChangePic(){

        //print(counter)
        if(counter == 15){
              counter = 0
        }

        let image: UIImage = UIImage(named: String(counter))!
        bgImage = UIImageView(image: image)
        bgImage.image = UIImage(named: String(counter))
        self.view.addSubview(bgImage!)
        counter = counter + 1

    }

Modifying the imageview here,this function is connected to a button in storyboard so that when you click it it changes the picture. the reason there is a counter is because the photos are enumerated from one 0-14 so I can easily display them. This works well enough but the images resize themselves and keep appearing on top of each other


Solution

  • If you just want to change the image you just have to do this:

    @IBAction func ChangePic(){
    
            //print(counter)
            if(counter == 15){
                  counter = 0
            }
    
            bgImage.image = UIImage(named: String(counter))
            counter = counter + 1
    
        }
    

    Your current code:

    @IBAction func ChangePic(){
    
            //print(counter)
            if(counter == 15){
                  counter = 0
            }
    
            // You create new image
            let image: UIImage = UIImage(named: String(counter))!
    
            // You set new instance to your imageView with your updated image (No need to do this because the object is not nil)
            bgImage = UIImageView(image: image)
    
            // You set again your updated image (only this line required )
            bgImage.image = UIImage(named: String(counter))
    
            // No needed
            self.view.addSubview(bgImage!)
    
    
            counter = counter + 1
    
        }