How to Add inline images with text in SwiftUI
Table of Contents
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("!")
}
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))
}
As you can see, you need to duplicate the same style over text and image, which is repetitive and error-prone.
You can easily support sarunw.com by checking out this sponsor.
Translate your app In 1 click: Simplifies app localization and helps you reach more users.
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"))!")
Style
Styling is as easy as this:
Text("Hello, \(Image(systemName: "globe"))!").font(Font.title.weight(.bold))
You can easily support sarunw.com by checking out this sponsor.
Translate your app In 1 click: Simplifies app localization and helps you reach more users.
Related Resources
Read more article about SwiftUI, String, or see all available topic
Enjoy the read?
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. No strings attached. Unsubscribe anytime.
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 Buy me a coffee Tweet ShareHow to declare Swift protocol for a specific class
Learn how to create protocols that constrain their conforming types to a given class.
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.