How to Add inline images with text in SwiftUI

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

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

If you enjoy this article, you can subscribe to the weekly newsletter.

Every Friday, you’ll get a quick recap of all articles and tips posted on this site — entirely for free.

← Home