Swift YYLabel处理Html富文本超链接跳转

一、返回html数据是: p标签, a标签包含的显示文本

 if let data = layout.data.data(using: .unicode) {
            if let attri = MSFHelper.setDocumentAttribute(type: .html, data: data, lineSpacing: 5, alignment: .left) {
                attri.enumerateAttributes(in: attri.yy_rangeOfAll(), options: []) { (attr: [NSAttributedString.Key: Any], range, stop) in
                    if let link = attr[NSAttributedString.Key.link] {
                        attri.yy_setTextHighlight(range, color: MSFColor.colorBlue62, backgroundColor: MSFColor.colorBlue62) { (containView, text, range, rect) in
                            Mprint("link: \(link)")
                            //  路由跳转
                            MSFRouter.navigationTo(schema: "\(link)")
                        }
                    }
                    nameLabel.attributedText = attri
                }
            }
        }
二、非HTML文本包含超链接,点击超链接跳转

使用如下:
let contentData = content.data(using: .unicode)!
if let contentAttri = MSFHelper.setDocumentAttribute(type: .html, data: contentData, lineSpacing: 1, alignment: .left, font: MSFFont.fontValue(size: 14, weight: .light)) {
       
contentLabel.attributedText = MSFHelper.getHyperLinkAttributeText(attri: contentAttri, font: MSFFont.fontValue(size: 14, weight: .light), underColor:MSFColor.colorBlue62, lightColor: MSFColor.colorBlue62)
}

// 懒加载显示超链接的label
private lazy var contentLabel: YYLabel = {
        let label = YYLabel()
        label.font = MSFFont.fontValue(size: 14, weight: .light)
        label.textColor = MSFColor.colorGray66
        label.textAlignment = .left
       // 点击超链接响应block
        label.highlightTapAction = { [weak self] (view, text, range, rect) in
            guard self != nil else {
                return
            }
            // 路由跳转
            MSFRouter.navigationTo(schema: text.attributedSubstring(from: range).string)
        }
        return label
 }()
三、工具类方法

3.1 设置Document类富文本
// 设置Document类富文本
    static func setDocumentAttribute(type: NSAttributedString.DocumentType, data: Data, lineSpacing: CGFloat, alignment: NSTextAlignment? = nil, font: UIFont? = nil) -> NSMutableAttributedString? {
        if data.count <= 0 {
            return nil
        }
        do {
            let attri = try NSMutableAttributedString.init(data: data, options: [NSAttributedString.DocumentReadingOptionKey.documentType: type], documentAttributes: nil)
            let paraph = NSMutableParagraphStyle()
            paraph.lineSpacing = lineSpacing
            paraph.alignment = alignment ?? .left
            attri.addAttributes([NSAttributedString.Key.paragraphStyle: paraph], range: NSMakeRange(0, attri.length))
            if let fontValue = font {
                attri.addAttribute(NSAttributedString.Key.font, value: fontValue, range: NSRange(location: 0, length: attri.length))
            }
            return attri
        } catch let error {
            Mprint(error)
        }
        return nil
    }
3.2 匹配超链接正则字符串
// 匹配超链接正则字符串
    static let urlRegular: String = "((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)"
3.3 获取YYText格式化的超链接
// 获取YYText格式化的超链接
    static func getHyperLinkAttributeText(attri: NSMutableAttributedString, font: UIFont? = nil, underColor: UIColor? = nil, radius: CGFloat = 3, lightColor: UIColor = MSFColor.colorYellow) -> NSMutableAttributedString? {
        if attri.string.count <= 0 {
            return nil
        }
        do {
            let regex: NSRegularExpression = try NSRegularExpression(pattern: MSFHelper.urlRegular, options: .caseInsensitive)
            let allMatches: [NSTextCheckingResult] = regex.matches(in: attri.string, options: .reportCompletion, range: NSRange(location: 0, length: attri.string.count))
            for match in allMatches {
                let attriForMatch: NSMutableAttributedString = NSMutableAttributedString.init(attributedString: attri.attributedSubstring(from: match.range))
                
                attriForMatch.yy_font = font ?? MSFFont.fontValue(size: 12, weight: .regular)
                attriForMatch.yy_underlineStyle = NSUnderlineStyle.single
                attriForMatch.yy_color = underColor ?? MSFColor.colorYellow
//
//                let border: YYTextBorder = YYTextBorder()
//                border.cornerRadius = radius
//                border.insets = UIEdgeInsetsMake(-2, -1, -2, -1)
                
                let highlight: YYTextHighlight = YYTextHighlight()
//                highlight.setBorder(border)
                highlight.setColor(lightColor)
                attriForMatch.yy_setTextHighlight(highlight, range: attriForMatch.yy_rangeOfAll())
                attri.replaceCharacters(in: match.range, with: attriForMatch)
            }
        } catch _ {
            Mprint("正则创建失败")
            return nil
        }
        return attri
    }

你可能感兴趣的:(Swift YYLabel处理Html富文本超链接跳转)