UIImage not displaying using Swift
Inorder to display images you have to change the code in following way
let image1 = UIImage(named: "img1.jpg")let imageview = UIImageView(image: image1)self.view.addSubview(imageview)let image2 = UIImage(named: "img2.jpg")let button = UIButton(frame: CGRect(origin: CGPoint(x: 0, y: 100), size: image2.size)button.setImage(image2, forState: UIControlState.Normal)self.view.addSubview(button)
Remember swift is not supporting .png format images, It is supporting .jpg format.
There seems to be a disconnect between the votes for the question and the other answers, so I will add a generic answer for how to display an image in Swift. That is what originally brought me here anyway.
How to display an image in Swift
Use UIImage
to get a reference to the image in the main bundle.
let image = UIImage(named: "rocket.png")imageView.image = image
Notes
imageView
is aUIImageView
- In my tests, including or excluding the .png file extension did not make a different. It might be necessary to include if you are using multiple image formats, though.
- Also in my tests, it did not make a difference whether the image was directly added to the project or was in Assets.xcassets.
- If you need an image that is not in the main bundle, see this question.
- According to the edit in the original question here, deleting the image and re-adding it to the bundle is what solved the problem.