86

I'm new to Swift and I want to load a special image from assets. For example I have:

image 1 for iphone 4s = green-square@2x.png
image 2 for iphone 5/5s = green-square-Retina@2x.png
image 3 for iphone 6s = green-square@3x.png

and I want to load for iphone 6 a specific image like

self.GSquare = SKSpriteNode(imageNamed: "./Images.xcassets/green-square-Retina@2x.png")

Is it possible?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Ghost
  • 903
  • 1
  • 6
  • 7

3 Answers3

146

You cannot load images directly with @2x or @3x, system selects appropriate image automatically, just specify the name using UIImage:

UIImage(named: "green-square-Retina")
Ely Dantas
  • 705
  • 11
  • 23
Azat
  • 6,745
  • 5
  • 31
  • 48
  • "green-square-Retina" doesn't load – Ghost Mar 30 '15 at 21:33
  • 1
    Make sure that it is there and have `png` extension – Azat Mar 30 '15 at 21:34
  • yes its there and it load automaticaly for iphone 5/5s but i want to use it also for iphone 6 because iphone 6 load iphone 4s image size, so i have done a detection for the current screen size so i can know that the current devise used is iphone 6 and then i load the retina image – Ghost Mar 30 '15 at 21:37
  • It is correct behavior, `@3x` loads only for iPhone 6 Plus. If you wish to force load other image, determine device type in runtime and use different image with another name, but this is not good approach – Azat Mar 30 '15 at 21:40
  • 2
    that's why i want to know if there is a possiblilty to do it directly because if i do for each image another one my application will get heavier – Ghost Mar 30 '15 at 21:43
  • You are following wrong approach in general. You may not use `Assets` and give each image personal name like `imageName-2x` and manually manage image loading. But it would be better to use it as intended – Azat Mar 30 '15 at 21:47
  • Thank you i will manage manually the iphone 6 only – Ghost Mar 30 '15 at 21:50
88

Since swift 3.0 there is more convenient way: #imageLiterals here is text example. And below animated example from here:

enter image description here

Maxim Kholyavkin
  • 4,463
  • 2
  • 37
  • 82
5

You can easily pick image from asset without UIImage(named: "green-square-Retina").

Instead use the image object directly from bundle.
Start typing the image name and you will get suggestions with actual image from bundle. It is advisable practice and less prone to error.

See this Stackoverflow answer for reference.

Roohul
  • 1,009
  • 1
  • 15
  • 26