skip to Main Content

I’m new to SwiftUI, and I want to place an image inside a text, similar to the example image below:

Example image

While I can add an image at the beginning of the label using

Label("You can also edit the text.", systemImage: "pencil.line")

I’d like the image to be integrated within the text.

2

Answers


  1. Two things you need to know:

    Thus:

    (
        Text("You can also ")
        + Text(Image(systemName: "pencil.line"))
        + Text(" edit the text.")
    )
    
    Login or Signup to reply.
  2. In SwiftUI, you can effortlessly combine multiple text elements into a single text by + operator and incorporate images within that text. Here’s how you can place an image inside your text:

    Text("You can also ")
     + Text(Image(systemName: "pencil.line"))
     + Text(" edit the text")
    

    Applying Modifiers:

    You have the flexibility to apply modifiers either individually or collectively to text elements.

    Collective Modifier Application:

    To apply modifiers collectively, enclose all text elements within the first set of parentheses and then apply the modifier as shown below:

    (Text("You can also ")
     + Text(Image(systemName: "pencil.line"))
     + Text(" edit the text"))
        .font(.title2)
        .fontWeight(.medium)
        .foregroundStyle(.green)
    

    Applying Modifiers Individually:

    You can easily apply modifiers to individual text elements, just as you would with any other view in SwiftUI.

    Text("You can also ")
        .font(.title2)
        .fontWeight(.medium)
        .foregroundStyle(.green)
    + Text(Image(systemName: "pencil.line"))
        .fontWeight(.bold)
        .foregroundStyle(.blue)
    + Text(" edit the text")
        .italic()
        .fontWeight(.bold)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search