user1940257
user1940257

Reputation:

Adding image resource to iOS app and access it

I have an Xcode project which needs to access an image. My questions are:

  1. How to add images to the Xcode project. Do I need to follow a specific structure or convention?
  2. How do I access the image I added in step (a)

Online links say add bundle resources but none of them gives a conclusive answer showing what to add in Xcode project and how to access the same.

Upvotes: 1

Views: 8084

Answers (4)

Raj Mohan
Raj Mohan

Reputation: 47

You will be able to find a folder named Assets.xcassets in your project hierarchy. enter image description here

Drag and drop the image you wish to add into this folder.Here you can select 1X 2X or 3X size for your image. enter image description here

After doing this you will have to create an UIImage object to access it. for example:

let image = UIImage(named:"image_name")

Now you can use this image object wherever you wish to use the image.

Upvotes: 1

Lynx
Lynx

Reputation: 401

When you create a project,there would be a folder named Assets.xcassets.You can drag the image you need into the Assets.xcassets. And when you need to show the image,code this:

//the image name is `image.jpg`
let image = UIImage(named : "image") 
imageView.image = image

PS: You can also drag the image to the project directly,and the code:

//the image name is `image.jpg`
let image = UIImage(named : "image.jpg") 
imageView.image = image

Upvotes: 1

Sanjeev Mishra
Sanjeev Mishra

Reputation: 59

Whenever you are creating a project, you getting a folder Assets.xcassets. In this just add a New Image Set, add the name which one is your image name and drop here 1x, 2x & 3x here. OR you can create a separate Asset Cataolog.

Upvotes: 0

Ankur Lahiry
Ankur Lahiry

Reputation: 2315

The best way to save image in your folder by creating an Asset Folder.

File -> New File -> Asset Catalog

enter image description here

Name the asset as image, it will create an asset folder image.xcassets

In this asset catalog, you will keep your images in specific folder.

you have to just write

imageView.image = UIImage(named : "MY_IMAGE_NAME") 

Upvotes: 2

Related Questions