Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift display image UIImageview

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

I am very new please go easy.

like image 672
Ljay Avatar asked Oct 04 '14 13:10

Ljay


1 Answers

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!

like image 195
NullHypothesis Avatar answered Oct 06 '22 20:10

NullHypothesis