How to add UIImageView programmatically in swift

You can add UIImageView programmatically in your iOS application  at run time. You can get the image file from server. To avoid complexity, we will use local image file. First create a new project. Copy and paste any image from your local computer in the project. You can download image from here.

UPDATE: After downloading the image, copy it to your project folder. Best way to do this is open the Project navigator of Xcode (If it is not already opened). Then open the folder where your image is located. Drag and drop the image from Finder to you Project Navigator. When a dialog box appear,  Check “Copy items if needed” to project option.

Before I proceed, let me explain the difference between UIImage and UIImageView.

UIImage: It’s the image that we want to display.

UIImageView: It’s something like frame of the image or placeholder of the image where we’ll set our UIImage or image.

Now open your ViewController.swift file.

There are 2 things to add image to your application programmatically.

1. Add image to your “image view”.

2. Add “image view” in your view.

In viewDidLoad method write the following code to add image to your image view:

Now, let’s add the image view in our main view:

We can also set width and height of the image:

The whole code is:

 

2 thoughts on “How to add UIImageView programmatically in swift”

    1. Hello, Thank you for noticing it. I’ve updated the article. Short answer is, place it anywhere in your project. Check the Update paragraph for details.

Leave a Reply