How to Add inline images with text in SwiftUI

⋅ 1 min read ⋅ SwiftUI String

HStack

Prior to iOS 14, we use HStack if we want to layout an image alongside any text.

HStack(spacing: 0) {
Text("Hello, ")
Image(systemName: "globe")
Text("!")
}
Layout an image with text using HStack
Layout an image with text using HStack

Styling

But it might be a bit cumbersome if you want to style both text and image. Let's say you want to apply title style and bold weight, you might need to do it like this.

HStack(spacing: 0) {
Text("Hello, ").font(Font.title.weight(.bold))
Image(systemName: "globe").font(Font.title.weight(.bold))
Text("!").font(Font.title.weight(.bold))
}
Title text style and bold weigth
Title text style and bold weigth

As you can see, you need to duplicate the same style over text and image, which is repetitive and error-prone.

String interpolation in iOS 14

In iOS 14 (Xcode 12 beta 3), we can insert images inline with any text with string interpolation.

Text("Hello, \(Image(systemName: "globe"))!")
Layout an image with text using HStack
Layout an image with text using HStack

Style

Styling is as easy as this:

Text("Hello, \(Image(systemName: "globe"))!").font(Font.title.weight(.bold))
Title text style and bold weigth
Title text style and bold weigth

Read more article about SwiftUI, String, or see all available topic

Feel free to follow me on Twitter and ask your questions related to this post. Thanks for reading and see you next time.

If you enjoy my writing, please check out my Patreon https://www.patreon.com/sarunw and become my supporter. Sharing the article is also greatly appreciated.

Become a patron Tweet Share
Previous
How to declare Swift protocol for a specific class

Learn how to create protocols that constrain their conforming types to a given class.

Next
How to renew an expired certificate with Fastlane Match

Fastlane Match saves us a lot of time managing certificates and provisioning profiles, but there is one thing that we have to do it manually. That is a renewal expired certificate. Luckily, we have to do it once a year. Let's learn how to do it.

← Home