【问题标题】:Is there a better way to change an Image in an ImageView by clicking a button?有没有更好的方法通过单击按钮来更改 ImageView 中的图像?
【发布时间】:2020-07-15 16:58:09
【问题描述】:

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

@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

    }

在此处修改图像视图,此功能连接到情节提要中的按钮,因此当您单击它时,它会更改图片。有一个计数器的原因是因为照片是从 0-14 枚举的,所以我可以轻松地显示它们。这工作得很好,但图像会自行调整大小并不断出现在彼此之上

【问题讨论】:

    标签: ios swift uibutton uiimageview uiimage


    【解决方案1】:

    既然你已经有了 imageView bgImage,你所要做的就是在 bgImage 上设置 image 属性。你不需要每次都创建一个新的 imageView。

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

    【讨论】:

      【解决方案2】:

      如果您只想更改图像,您只需这样做:

      @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
      
          }
      

      【讨论】:

        猜你喜欢
        • 2019-12-03
        • 2018-06-16
        • 2012-08-18
        • 2014-04-17
        • 2015-10-16
        • 2015-08-17
        • 1970-01-01
        • 2020-12-30
        • 1970-01-01
        相关资源
        最近更新 更多