UIImage(named: String) or UIImage swift 4

10,226

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

Share:
10,226

Related videos on Youtube

Fedir Kryvyi
Author by

Fedir Kryvyi

Updated on June 26, 2022

Comments

  • Fedir Kryvyi
    Fedir Kryvyi almost 2 years

    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]
    
    • rmaddy
      rmaddy almost 6 years
      @ElTomato Given the nature of the question I think you should provide reasons for your statement.
  • El Tomato
    El Tomato almost 6 years
    "Approach one is an ok approach." Really?
  • Elhoej
    Elhoej almost 6 years
    Why not @El Tomato?
  • El Tomato
    El Tomato almost 6 years
    @Elhoej Ask Google, Yahoo or whoever about UIImage memory crash
  • Elhoej
    Elhoej almost 6 years
    I see, but that only occurs for huge data arrays. For 6 images its fine to use an array of image literals.
  • Fedir Kryvyi
    Fedir Kryvyi almost 6 years
    Thanks for your answer
  • Alex Kolovatov
    Alex Kolovatov over 4 years
    Also you can use #color literal to use ColorSet from your Assets catalog.

Related