如何从同一功能获得多个归因?

时间:2018-10-02 12:35:42

标签: swift hyperlink nsmutableattributedstring

我这样使用attributed text

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

detailText.attributedText = formated

使用此功能:

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

问题是,我想在文本中包含两个(或多个)链接(第二个HERE)。但是我不能第二次调用该函数。我需要添加多个参数吗?

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

有更好的动态方式吧?

更新 有建议将链接作为字典发送到数组中,但我不知道如何解压缩它:

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"]])) 
}

1 个答案:

答案 0 :(得分:0)

您可以使用Array,然后改进func formatHyperlink(text: String, link: String, linkStart: Int, linkEnd: Int)

如何使用structure

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

然后:

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

    //Construct the NSMutableAttributedString

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

致电:

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

侧面说明: 未经测试的代码,可能不会因普通的拼写错误而编译。