Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIImage(named: String) or UIImage swift 4

What way is more convenient to set image from my app assets in my app Image View? I have two ways: the first one is function UIImage(named: String) or UIImage and both is working for me, but I want to know which one is the best ,so I can use one in the future

here is two examples

//  first

 let myImages1 = ["dice1", "dice2", "dice3", "dice4", "dice5", "dice6"]

 @IBOutlet weak var diceImageView1: UIImageView!

 diceImageView1.image = UIImage(named: myImages1[index1])

// second

 let myImages2 = [ image1, image2, image3, image4, image5, image6 ]

 @IBOutlet weak var diceImageView2: UIImageView!

 diceImageView2.image = myImages2[index2]
like image 726
Fedir Kryvyi Avatar asked Jun 24 '18 22:06

Fedir Kryvyi


1 Answers

We're using Images from assets catalog instead String names. It's the better way to set UIImage. But from swift 4.2 we can't use asset names anymore. We should use image literal. Here's the example:

let logoImageView: UIImageView = {
    let iv = UIImageView()

    // Set image with image literal
    iv.image = #imageLiteral(resourceName: "feedback")
    return iv
}()

Look at the screenshot below.

enter image description here

After you've typed Image Literal you can double click on that and choose your image from assets catalog. Here is the screenshot.

enter image description here

But last time I use this lib R.swift. Get strong typed, autocompleted resources like images, fonts and segues in Swift projects.

How it looks in code:

enter image description here

like image 94
Alex Kolovatov Avatar answered Sep 26 '22 09:09

Alex Kolovatov