如何在UITextview中呈现具有不同字体样式但具有相同字体系列的HTML字符串 [英] How to render HTML string in UITextview with different font styles but same font family

查看:112
本文介绍了如何在UITextview中呈现具有不同字体样式但具有相同字体系列的HTML字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的HTML字符串:

This is my HTML string:

<i>Italics </i><b>Bold </b><u>Underline</u><blockquote>block quote<br></blockquote>

我希望所有样式都相同(斜体,粗体等),但是我想将字体系列实现为Open Sans.因此,无论斜体是什么,我都希望字体为Open-Sans Italics.我该如何实施?请帮忙.

I want all the styling to be same (Italic, bold etc), but I want to implement the font family as Open Sans. So, wherever its italics I want the font to be Open-Sans Italics. How do I implement that? Please help.

推荐答案

尝试使用带有NSHTMLTextDocumentType选项和.utf8字符串编码的NSAttributedString

try using NSAttributedString with NSHTMLTextDocumentType option and .utf8 string encoding

快捷键3:

extension String {

    var htmlAttributedString: NSAttributedString? {

        do {
            return try NSAttributedString(data: data(using: .utf8)!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil)
        } catch let error {
            print(error.localizedDescription)
        }
        return nil
    }
}

使用

let htmlStringCode = "<i>Italics </i><b>Bold </b><u>Underline</u><blockquote>block quote<br></blockquote>"

if let htmlText = htmlStringCode.htmlAttributedString {
       let attributes = [NSFontAttributeName: UIFont(name: "Open Sans", size: 18.0)!]
        let attributedText = NSMutableAttributedString(string: htmlText.string, attributes: attributes)

        let htmlString = htmlText.string as NSString
        let range  = htmlString.range(of: "Italics")
        attributedText.addAttribute(NSFontAttributeName, value: UIFont(name: "OpenSans-Italic", size: 18.0)!, range: range)

        textView.attributedText = attributedText
}

这篇关于如何在UITextview中呈现具有不同字体样式但具有相同字体系列的HTML字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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