NEW: Get your ticket for Hacking with Swift Live 2019! >>

< How to format text inside text views   How to adjust the way an image is fitted to its space >

How to draw images using Image views

Use the Image view to render images inside your SwiftUI layouts. These can load images from your bundle, from system icons, from a UIImage, and more, but those three will be the most common.

To load an image from your bundle and display it inside an image view, you’d just use this:

var body: some View {
    Image("example-image")
}

Note: I’m not going to repeat the var body: some View { part from now on – you get the idea. In the future I’ll show it only when it really matters.

To load icons from Apple’s San Francisco Symbol set, use the Image(systemName:) initializer, passing in the icon string to load, like this:

Image(systemName: "cloud.heavyrain.fill")

Finally, you can create an image view from an existing UIImage. As this requires more code, you’ll need to use the return keyword explicitly:

guard let img = UIImage(named: "example-image") else {
    fatalError("Unable to load image")
}

return Image(uiImage: img)

If you’re using the system icon set, the image you get back is scalable and colorable, which means you can tint the image using the same foregroundColor() modifier you’ve already seen:

Image(systemName: "cloud.heavyrain.fill")
    .foregroundColor(.red)

And it also means you can ask SwiftUI to scale up the image to match whatever Dynamic Type text style it accompanies, if any:

Image(systemName: "cloud.heavyrain.fill")
    .font(.largeTitle)

HACKING WITH SWIFT LIVE This July is a new two-day event where you'll be inspired by great speakers on day one then learn all the amazing new features from WWDC on day two – click here for more information and tickets.

< How to format text inside text views   How to adjust the way an image is fitted to its space >
MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Average rating: 4.9/5

Click here to visit the Hacking with Swift store >>