0

I am trying to add a UIImage to a UIImageView in Swift as of March 2019. The image is titled correctly and is saved in the iCloud Drive in the same directory as the Swift file. I am able to add the UIImageView to a view controller perfectly fine but the image does not show up in it. I believe I have the right file name as I copied it directly from the finder. What I want to do is have an image inside of a viewer which is scaled by aspect ratio to fit the viewer.

let discoverIcon = UIImage(named: "DiscoverButtonIcon.png")
    let discoverImageView = UIImageView(frame: CGRect(x: 200, y: 200, width: 100, height: 100))
    discoverImageView.image = discoverIcon
    discoverImageView.contentMode = .scaleAspectFit
    view.addSubview(discoverImageView)

This is what I have tried to do but the UIImage will not show up.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • I used your code in a viewDidLoad method and I actually got an image in pointed out position. So I recommend you to debug your code: set breakpoint on `discoverImageView.image = discoverIcon` and make 1 step and in console type: `po discoverImageView.image`. You have to receive some image in a result – Volodymyr Mar 16 '19 at 22:23

3 Answers3

2

Temporarily change

UIImage(named: "DiscoverButtonIcon.png")

To

UIImage(named: "DiscoverButtonIcon.png")!

Run the app. If it crashes, you have the wrong name or the image is not in your app bundle at all.

is saved in the iCloud Drive in the same directory as the Swift file

That sounds like the problem. That is not where the image needs to be. It needs to be in your asset catalog or app bundle.

matt
  • 515,959
  • 87
  • 875
  • 1,141
2

The best practice would be adding the image to assets folder. By adding the image your assets.xcassets it will be added to your Bundle Resources.

If you don't want to add it to the assets.xcassets folder, add the image as another item in your project. However, make sure you add the image to the right target. (You can check in File Inspector > Target Membership)

  • You can check Build Phases > Copy Bundle Resources to make sure that you add the image to the Bundle correctly.
// If you add image to assets.xcassets
let image = UIImage(named: "DiscoverButtonIcon")

// If you add image as a resource
let image = UIImage(named: "DiscoverButtonIcon.png")

// Set a break point here to debug your image.
Get Schwifty
  • 161
  • 2
  • 3
1

Try to add your image to Images.xcassets.

Anton
  • 111
  • 10