Programmatically set image to UIImageView with Xcode 6.1/Swift

How about this;

myImageView.image=UIImage(named: "image_1")

where image_1 is within the assets folder as image_1.png.

This worked for me since i'm using a switch case to display an image slide.


In xcode 8 you can directly choose image from the selection window (NEW)...

  • You just need to type - "image" and you will get a suggestion box then select -"Image Literal" from list (see in attached picture) and

  • then tap on the square you will be able to see all images(see in
    second attached picture) which are in your image assets... or select other image from there.

enter image description here

  • Now tap on square box - (You will see that square box after selecting above option)

enter image description here


Since you have your bgImage assigned and linked as an IBOutlet, there is no need to initialize it as a UIImageView... instead all you need to do is set the image property like bgImage.image = UIImage(named: "afternoon"). After running this code, the image appeared fine since it was already assigned using the outlet.

enter image description here

However, if it wasn't an outlet and you didn't have it already connected to a UIImageView object on a storyboard/xib file, then you could so something like the following...

class ViewController: UIViewController {
    var bgImage: UIImageView?

    override func viewDidLoad() {
        super.viewDidLoad()

        var image: UIImage = UIImage(named: "afternoon")!
        bgImage = UIImageView(image: image)
        bgImage!.frame = CGRectMake(0,0,100,200)
        self.view.addSubview(bgImage!)
    }
}

OK, got it working with this (creating the UIImageView programmatically):

var imageViewObject :UIImageView

imageViewObject = UIImageView(frame:CGRectMake(0, 0, 600, 600))

imageViewObject.image = UIImage(named:"afternoon")

self.view.addSubview(imageViewObject)

self.view.sendSubviewToBack(imageViewObject)

Tags:

Ios

Xcode

Swift