Getting the range of links in attributed string

后端 未结 1 1008
礼貌的吻别
礼貌的吻别 2021-01-28 10:11

I would like to find the range of links in attributed text, so I could apply custom underline only to the relevant words.

At the moment, the underline is under all of th

相关标签:
1条回答
  • 2021-01-28 10:11

    With:

    let attributedText = htmlStyleAttributeText(text: text)!
    ...
    textView.attributedText = attributedText
    

    Separate the attributes:

    let underlinesAttributes: [NSAttributedString.Key: Any] = [.underlineStyle: 0x15,
                                                               .underlineColor: underLineColor]
    
    let attributes: [NSAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: 25),
                                                     .baselineOffset: 0]
    

    Apply the "basic ones" to the whole text:

    let wholeRange = NSRange(attributedText.string.startIndex..., in: attributedText.string)
    storage.addAttributes(attributes, range: wholeRange)
    

    We now enumerate looking for the links, and apply the effect for each one found:

    attributedText.enumerateAttribute(.link, in: wholeRange, options: []) { (value, range, pointee) in
        if value != nil {
            storage.addAttributes(underlinesAttributes, range: range)
        }
    }
    
    0 讨论(0)
提交回复
热议问题