How to display [Link]?

In SwiftUI, how to display a [Link<Text>]?

Answered by BabyJ in 728676022

What do you mean by "displaying" the links?

(1) Is it showing them repeatedly in a row/column? (2) Or do you want the links to be interpolated in some standard text?


I would recommend using an array of a custom type that can then each be converted into a Link view, instead of storing the actual view.

Something like this:

struct DisplayedLink {
    let title: String
    let url: URL
}

let links: [DisplayedLink] = [
    ...
]



Option 1:

// any suitable layout container
VStack {
    ForEach(links, id: \.self) { link in
        Link(link.title, destination: link.url)
    }
}


Option 2:

var linksText: AttributedString {
    var str = AttributedString("text comprised of the links' titles")

    for link in links {
        if let range = str.range(of: link.title) {
            str[range].link = link.url
        }
    }

    return str
}

// the linked text is coloured and tappable
Text(linksText)

You can use it like this:

Link("Click this link", destination: URL(string: "https://some.destination.url")!)


The init(_:destination:) initialiser will convert the title string parameter to a Text object, hence getting you to your Link<Text> object.


Check out the documentation for more.

To clarify the question: how to display an Array of Links?

Accepted Answer

What do you mean by "displaying" the links?

(1) Is it showing them repeatedly in a row/column? (2) Or do you want the links to be interpolated in some standard text?


I would recommend using an array of a custom type that can then each be converted into a Link view, instead of storing the actual view.

Something like this:

struct DisplayedLink {
    let title: String
    let url: URL
}

let links: [DisplayedLink] = [
    ...
]



Option 1:

// any suitable layout container
VStack {
    ForEach(links, id: \.self) { link in
        Link(link.title, destination: link.url)
    }
}


Option 2:

var linksText: AttributedString {
    var str = AttributedString("text comprised of the links' titles")

    for link in links {
        if let range = str.range(of: link.title) {
            str[range].link = link.url
        }
    }

    return str
}

// the linked text is coloured and tappable
Text(linksText)
How to display [Link]?
 
 
Q