Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIImage not displaying using Swift

Tags:

ios

swift

uiimage

Code written in Swift for displaying UIImages works in the iOS 8.0 simulator but not on a phone running IOS 7.0 for some reason.

let image1 = UIImage(named: "img1")
let imageview = UIImageView(image: image1)
self.view.addSubview(imageview)

let image2 = UIImage(named: "img2")
let button = UIButton(frame: CGRect(origin: CGPoint(x: 0, y: 100), size: image2.size)
button.setImage(image2, forState: UIControlState.Normal)
self.view.addSubview(button)

The images are in the right place with the right size and valid references, they're just not being displayed, except on the simulator running iOS 8.

Is this a problem for anyone else?

EDIT: Deleting from Images.xcassets, cleaning the project and copying the files into the bundle itself seems to work for me.

like image 347
Joseph Mark Avatar asked Jun 04 '14 08:06

Joseph Mark


3 Answers

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.

like image 119
CNU Avatar answered Oct 22 '22 11:10

CNU


You would check if the image was added to your framework, if that is unchecked you are not able to load the resource, but if you check it, the image will be loaded enter image description here

like image 28
Benjamin RD Avatar answered Oct 22 '22 12:10

Benjamin RD


I tried your code in iOS 8-Simulator and on my iOS 7 device and it did what it should do. So no, in my case I don't see a problem.

I changed img1 to img1.JPG (name of file) and img2 to img2.png. And I copied the images directly into the folder where the view controller is..

like image 35
Ben Avatar answered Oct 22 '22 11:10

Ben