How to load and display an image on iOS App using Swift?


To load and display an image in iOS app we’ll first need to get an image.

Then we’ll drag that image to our project and select copy if required option and our application target.

Let’s see the rest with help of an example.

Now, we’ll create an UIImageView and assign the image to its image property, for that we’ll create a function.

func addImage(imageName img: String) {
   let imageView = UIImageView()
   imageView.frame = self.view.frame
   imageView.contentMode = .scaleAspectFit
   if let newImage = UIImage(named: img) {
      imageView.image = newImage
   }
   self.view.addSubview(imageView)
}

Now, we’ll call this code in our viewDidLoad or any other place where we need.

override func viewDidLoad() {
   super.viewDidLoad()
   self.addImage(imageName: "1.png")
}

When we run the above code on our application it produces the following result.

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

813 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements