如何使NSMutableAttributedString用于链接?

时间:2018-10-03 09:59:34

标签: swift hyperlink nsmutableattributedstring

我正在使用NSMutableAttributedString设置文本字符串的格式。即使使用链接,它也可以正常工作。但是由于某些原因,即使我指定了大小,链接的字体大小也不会改变。我的函数如下所示:(代码中包含注释以解释所有内容)

func formatfunc2(chapter: String, boldStart: Int, boldLength: Int, italicsStart: Int, italicsLength: Int, link: [String], linkStart: [Int], linkEnd: [Int]) -> NSAttributedString {

    let bold = UIFont.boldSystemFont(ofSize: 17)
    let italics = UIFont.italicSystemFont(ofSize: 17)

    //BELOW IS MY FORMAT FOR THE HYPERLINK
    let hyperlink = UIFont.boldSystemFont(ofSize: 17)

    let attributedString = NSMutableAttributedString.init(string: chapter, attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 17)])

    //BELOW ARE FORMAT FOR BOLD AND ITALICS - AND THEY WORK FINE
    attributedString.addAttribute(.font, value: bold, range: NSRange.init(location: boldStart, length: boldLength))
    attributedString.addAttribute(.font, value: italics, range: NSRange.init(location: italicsStart, length: italicsLength))

    //THE LOOP GOES THROUGH ALL LINK ADRESSES AND THEIR POSITIONS
    for i in 0...link.count - 1 {

        //HERE I ADD THE FONT SIZE TO THE SAME POSITION AS THE LINKS, BUT IT DOESN'T WORK 
        attributedString.addAttribute(.font, value: hyperlink, range: NSRange.init(location: linkStart[i], length: linkEnd[i]))

        let url = URL(string: link[i]) as! URL

        //MY THEORY IS THAT THE CODE BELOW OVERRIDES THE PREVIOUS FONT SIZE
        attributedString.setAttributes([.link: url], range: NSMakeRange(linkStart[i], linkEnd[i]))
    }

    return attributedString
}

因此,该格式适用于所有其他文本,但不适用于links。我可以在最后的代码部分中添加字体大小吗? :

attributedString.setAttributes([.link: url], range: NSMakeRange(linkStart[i], linkEnd[i]))

0 个答案:

没有答案