0

I'm using attributed text like this:

let formated = textAnhorig.formatHyperlink(text: "click HERE and HERE", link: www.test.com, linkStart: 6, linkEnd: 9)

detailText.attributedText = formated

Using this function:

func formatHyperlink(text: String, link: String, linkStart: Int, linkEnd: Int) { 
    let attributed = NSMutableAttributedString(string: text) 
    let url = URL(string: link) 
}

Problem is, I want to have two (or more) links in the text (The second HERE). But I can't call the function a second time. Do I need to add multiple arguments, like this:

let formated = textAnhorig.formatHyperlink(text: "click HERE and HERE", link: www.test.com, linkStart: 6, linkEnd: 9, link2: www.test2.com, linkStart: 15, linkEnd18)

There's goto be a better more dynamic way right?

UPDATE Got a suggestion to send the links as dictionaries in an array, but I don't know how to unpack it:

var dict1 = ["link": "www.test.com", "start": 0, "end": 10] as [String : Any] 
var dict1 = ["link": "www.test2.com", "start": 22, "end": 66] as [String : Any] 
var array = [dict1, dict2]


for i in array { 
    let url = URL(string: array[i["link"]]) 
    attributed.setAttributes([.link: url], range: NSMakeRange(array[i["start"]], array[i["end"]])) 
}
tore
  • 619
  • 2
  • 9
  • 23
  • That's a strange way to use it, but what about having: `formatHyperlink(text: String, links:[[String: Any]])` `links` being an array of dict (or custom struct), holding the link and the "ranges" (indices)? – Larme Oct 02 '18 at 15:54
  • Is it strange? Am I doing it wrong? How else do you create hyperlinks. Thanks though, I'll try :) – tore Oct 02 '18 at 20:48
  • How would I unpack it? See main post... – tore Oct 02 '18 at 21:20
  • `array[i["link"]]` => `array[i]["link"]`. (same for the other ones). Also, `array` needs to be defined as `[[String: Any]]`, and you might specify with `as` that's the elements are `String` (link) or `Int` (range start/length) – Larme Oct 03 '18 at 10:26

1 Answers1

0

You could use an Array and then improve func formatHyperlink(text: String, link: String, linkStart: Int, linkEnd: Int)

What about using a structure:

struct LinkAttributes {
    let url: String
    let range: NSRange
}

Then:

func formatHyperlink(text: String, links: [LinkAttributes]) {

    //Construct the NSMutableAttributedString

    for aLinkAttribute in LinkAttributes {
        attributedString.addAttribute(.link, value: aLinkAttribute.url, range: aLinkAttribute.range)
    }
}

Call:

formatHyperlink(text: "someString", 
                links:[LinksAttributes(url: url1, range: NSMakeRange(location: 0, end: 10)), 
                       LinksAttributes(url: url1, range: NSMakeRange(location: 22, end: 66))]

Side Note: Code not tested, might not compile for a trivial typo error.

Larme
  • 24,190
  • 6
  • 51
  • 81