How to underline a substring in a Text in SwiftUI?

Viewed 1973

Is there a way to underline online a specific substring inside Text view in Swift UI?

// Code bellow will underline the ENTIRE string 
// Any way to underline on a specific substring?
Text("You must be invited by an....")
    .underline()

Here is specifically the UI I am trying to build:

2 Answers

Text(..) views have a + operator that combines texts. Haven't looked how this magic works yet, but it does the job really well.

 Text("Regular text... ")
     + Text("underlined text!")
         .underline()

There is also as second way of doing this as well using a underlined() function on string:

 Text("Regular text... " + "undelined text!".underlined())

Super cool!

What worked for me was using String Interpolation with other Text objects.

e.g.

Text("This sentence is not underlined. \(Text("But this sentence is underlined.").underline())")

Using this strategy I was able to interpolate three different underlined Text objects within the original Text object without the compiler complaining.

Hope this helps!

Related