Zorayr
Zorayr

Reputation: 24962

How to underline a substring in a Text in SwiftUI?

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:

Upvotes: 10

Views: 8293

Answers (3)

Patrick Ridd
Patrick Ridd

Reputation: 493

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!

Upvotes: 14

Dheeraj Gupta
Dheeraj Gupta

Reputation: 380

There are several ways to achieve it. I will mention using AttributedString()

func getAttributedString(string: String) -> AttributedString {
        var attributedString = AttributedString(string)
        attributedString.font = .body.bold()
        attributedString.underlineStyle = .single
        return attributedString
}

Here, in the function I have also added bold along with underline, you can add more styles. This can stay in the ViewModel class and call from View like this:

Text("You must be invited by an...." + model. getAttributedString(string: "apply to be on the waitlist"))

Or there is another way, you can create another function in ViewModel that would do what I have shown above like this.

Text(model.getString())  // put this in View

func getString() -> AttributedString {
    return "You must be invited by an...." + getAttributedString(string: "apply to be on the waitlist")
}

Upvotes: 1

Zorayr
Zorayr

Reputation: 24962

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!

Upvotes: 13

Related Questions