In this tutorial, I am going to show you how to insert images into text in SwiftUI Text views. The purpose of doing this task is to add inline images to our text.
SwiftUI allows us to directly put images in Text view as you can see below:
Text("I \(Image(systemName: "heart.fill")) SwiftUI")
You can also use a separate Text view for inserting images and then combine them. In this tutorial, you can see how to combine multiple text views – Combine multiple Text views together in SwiftUI.
Below is how you can insert an image into text by combining multiple text views:
Text("I ") + Text(Image(systemName: "heart.fill")) + Text(" SwiftUI")
As you can see, the result is the same as the previous one. Now you may think, what is the meaning of using multiple text views? Let me explain.
Suppose you want the heart icon in a different color. If you use a separate text view, then you can easily apply the foreground color to it. In the example below, we are giving red color to the heart icon:
Text("I ") + Text(Image(systemName: "heart.fill")) .foregroundColor(.red) + Text(" SwiftUI")
As you can see in the figure, the heart icon is now red.
You can also take all the text views inside parenthesis and apply the style that affects all except the one you set the style separately:
( Text("I ") + Text(Image(systemName: "heart.fill")) .foregroundColor(.red) + Text(" SwiftUI") ) .foregroundColor(.green)
You can see that all the texts are in green. But the image of the heart is still in the red. This is because we set the foreground color for that text view separately inside the parenthesis. Declaring any modifier inside the parenthesis can not be replaced by the outer modifier. In our case, the green color can not change the red color we declared for the heart icon.