Swift display image UIImageview

非 Y 不嫁゛ 提交于 2019-12-10 16:52:07

问题


How can I display image inside UIImageview? Then change images according to pressed button.

I am very new please go easy.


回答1:


To do this, first make sure you have the image available in the viewcontroller (by creating an association between the image on your storyboard, and in your viewcontroller).

Let's pretend it's called imageView.

Programmatically, you can say:

  imageView.image = UIImage(named: ("nameofasset"))

What I actually ended up doing is creating a static function responsible for determining which image to return as such:

class func GetImage(someValueWhichDrivesLogic: Int)->UIImage
{
    if (someValueWhichDrivesLogic == 1)
    { 
      assetName = "imageone" //note you don't add .png, you just give it the same name you have in your standard images folder in XCode6
    }
    else if (someValueWhichDrivesLogic == 2)
    {
      assetName = "imagetwo" //again, this is the actual name of my image
    }

    //Return an image constructed from what existed in my images folder based on logic above
    return UIImage(named: (assetName))

}

So now that the function above has been created, you could just do something like this:

 imageView.image = GetImage(1) 
 imageView.image = GetImage(2) 

This would actually assign the images dynamically to the image. You could just do this, or if you're literally doing something as simple as putting it into a button click you can just take the easier approach I specified above.

Thanks let me know if any questions!



来源:https://stackoverflow.com/questions/26193132/swift-display-image-uiimageview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!