Other way to set an image?

I strugeled with some images I put in different folders in Assets.

Some images are named equal in different folders.


Problem is now that I found just this method to set a new image in source code:

MyImage.image = UIImage(named: "Y")


So if I have one image "Y" in "Folder1" and one image "Y" in "Folder2" Xcode cannot distinguish between them.



Is there a way to do this with paths?


Like MyImage.imageUrl = "Folder1/Y" or MyImage.imageUrl = "Folder2/Y" would be fine.


Thanks!

Accepted Reply

There is another initializer for UIImage with which you can specify bundle.


Should that answer your need ?


PS: it is not a very good idea to ginve the same name to different resources, even if in different folders. You will get confused one day or another.


Initializerinit(named:in:compatibleWith:)


Returns the named image that is also compatible with the specified trait collection.


Declaration

init?(named name: String, in bundle: Bundle?, compatibleWith traitCollection: UITraitCollection?)

Parameters

name

The name of the image. For images in asset catalogs, specify the name of the image asset. For PNG image files, specify the filename without the filename extension. For all other image file formats, include the filename extension in the name.

bundle

The bundle containing the image file or asset catalog. Specify

nil
to search the app’s main bundle.
traitCollection

The traits associated with the intended environment for the image. Use this parameter to ensure that the correct variant of the image is loaded. If you specify

nil
, this method uses the traits associated with the main screen.


Replies

There is another initializer for UIImage with which you can specify bundle.


Should that answer your need ?


PS: it is not a very good idea to ginve the same name to different resources, even if in different folders. You will get confused one day or another.


Initializerinit(named:in:compatibleWith:)


Returns the named image that is also compatible with the specified trait collection.


Declaration

init?(named name: String, in bundle: Bundle?, compatibleWith traitCollection: UITraitCollection?)

Parameters

name

The name of the image. For images in asset catalogs, specify the name of the image asset. For PNG image files, specify the filename without the filename extension. For all other image file formats, include the filename extension in the name.

bundle

The bundle containing the image file or asset catalog. Specify

nil
to search the app’s main bundle.
traitCollection

The traits associated with the intended environment for the image. Use this parameter to ensure that the correct variant of the image is loaded. If you specify

nil
, this method uses the traits associated with the main screen.