获取属性字符串中的链接范围 [英] Getting the range of links in attributed string

查看:63
本文介绍了获取属性字符串中的链接范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在属性文本中找到链接的范围,因此我只能将自定义下划线应用于相关词.

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 the text.

我希望它只在链接下.

I want it to be only under the links.

由于所请求的下划线是超级定制的,因此代码有点复杂.

The code is a bit complex as the requested underline is super customised.

import UIKit

class ViewController: UIViewController {

        override func viewDidLoad() {
            super.viewDidLoad()

            let text = "random text <a href='http://www.google.com'>http://www.google.com </a> more random text"

            let storage = NSTextStorage()
            let layout = UnderlineLayout()
            storage.addLayoutManager(layout)
            let container = NSTextContainer()
            layout.addTextContainer(container)

            let textView = UITextView(frame: CGRect(x: 30, y: 380, width: 300, height: 200), textContainer: container)
            textView.isUserInteractionEnabled = true
            textView.isEditable = false
            textView.textContainerInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
            textView.attributedText = htmlStyleAttributeText(text: text)
            textView.backgroundColor = UIColor.white
            textView.textColor = UIColor.black

            let underLineColor: UIColor = UIColor(red: 245/255, green: 190/255, blue: 166/255, alpha: 1)


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

            let rg = NSRange(location: 0, length: textView.attributedText!.string.count)

            storage.addAttributes(attributes, range: rg)
            view.addSubview(textView)
        }

        public func htmlStyleAttributeText(text: String) -> NSMutableAttributedString? {

            if let htmlData = text.data(using: .utf8) {

                let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html, NSAttributedString.DocumentReadingOptionKey.characterEncoding: String.Encoding.utf8.rawValue]
                let attributedString = try? NSMutableAttributedString(data: htmlData, options: options, documentAttributes: nil)

                return attributedString
            }
            return nil
        }
}


import UIKit

class UnderlineLayout: NSLayoutManager {
    override func drawUnderline(forGlyphRange glyphRange: NSRange, underlineType underlineVal: NSUnderlineStyle, baselineOffset: CGFloat, lineFragmentRect lineRect: CGRect, lineFragmentGlyphRange lineGlyphRange: NSRange, containerOrigin: CGPoint) {
        if let container = textContainer(forGlyphAt: glyphRange.location, effectiveRange: nil) {
            let boundingRect = self.boundingRect(forGlyphRange: glyphRange, in: container)
            let offsetRect = boundingRect.offsetBy(dx: containerOrigin.x, dy: containerOrigin.y)

            let left = offsetRect.minX
            let bottom = offsetRect.maxY
            let width = offsetRect.width
            let path = UIBezierPath()
            path.lineWidth = 4
            path.move(to: CGPoint(x: left, y: bottom))
            path.addLine(to: CGPoint(x: left + width, y: bottom))
            path.stroke()
        }
    }
}

推荐答案

使用:

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

分隔属性:

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

这篇关于获取属性字符串中的链接范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆