有没有更好的方法通过单击按钮来更改 ImageView 中的图像?

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

目前我正在通过执行以下操作更改图像视图:

@IBOutlet var bgImage: UIImageView!

创建在故事板中连接的 UIimage 视图 和

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

    }

在这里修改imageview,这个函数连接到故事板中的一个按钮,所以当你点击它时它会改变图片。有一个计数器的原因是因为照片是从 0-14 中列举出来的,所以我可以很容易地显示它们。这很好用,但图像会自行调整大小并不断出现在彼此之上

由于您已经有了 imageView bgImage,您所要做的就是在 bgImage 上设置图像 属性。您不需要每次都创建一个新的 imageView。

@IBAction func ChangePic(){

   if(counter == 15){
          counter = 0
    }
    bgImage.image = UIImage(named: String(counter))
    counter = counter + 1
}

如果您只想更改图片,只需执行以下操作:

@IBAction func ChangePic(){

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

        bgImage.image = UIImage(named: String(counter))
        counter = counter + 1

    }

您当前的代码:

@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

    }