Effortlessly Set Colors and Images in Your Code with Color and Image Literals in SwiftUI

Color and image literals are handy tools that allow you to set colors and images directly in your code without having to specify the values manually. With color literals, you can use the built-in color picker to choose the color you want and insert it into your code as a literal value. Similarly, image literals allow you to insert images from your asset catalog directly into your code without having to reference them by name.

Using color and image literals not only saves you time, but also ensures that the correct color or image is used in your app. In this way, you can ensure that your app's appearance is consistent across all platforms and devices.

Xcode has the ability to embed colors and images directly in code. This is done with the help of Color Literals and Image Literals. 

Color Literal 

A color literal allows you to select colors using a color picker directly from your code. You can either select a color or type in the HEX code. You can also set the opacity.


Note
: Color literals are great for static colors. For colors that adapt to dark mode, I suggest using colors in the Assets Catalog.

Code:
let color0 = Color(#colorLiteral(red: 0.5568627715, green: 0.3529411852, blue: 0.9686274529, alpha: 1));

let color1 = Color(#colorLiteral(red: 0.3647058904, green: 0.06666667014, blue: 0.9686274529, alpha: 1));
..


Image Literal 
Similar to color literals, image literals opens up a GUI from where you can select all the images in your Assets Catalog.



You can download free images from https://www.freepik.com/.

 var body: some View {
    
        let image0 = #imageLiteral(resourceName: "fish1")
        
        VStack {
            Image(uiImage: image0)
        }
    
    }

..


Comments