swiftswiftuihyperlinklocalizedstringkey

SwiftUI Underlined Hyperlinks


I am using hyperlinks in SwiftUI which are highlighted, but I also want them to be underlined as well. Is that possible?

Text("This [link](https://google.com) goes to google")

How can I make the link part underlined?


Solution

  • You can search for link runs in the attributed string and based on their ranges modify the attributes of the main string:

    let baseString = "Hello [World](https://www.google.com) this is [Google](https://www.yahoo.com)"
    var text = try! AttributedString(markdown: baseString)
    let runsWithLinks = text.runs.filter { run in
        run.link != nil
    }
    
    for run in runsWithLinks {
        text[run.range].font = .system(size: 18).monospaced() // extra example
        text[run.range].foregroundColor = .gray               // extra example
        text[run.range].underlineStyle = .init(pattern: .solid, color: .green)
    }
    

    Previewing the above example yields this result:

    enter image description here

    During my testing, using .underlineColor had no effect. I'm not sure why.