如何使用不同的字体样式但相同的字体系列在UITextview中呈现HTML字符串

时间:2017-01-17 07:58:56

标签: ios objective-c fonts html-parsing richtext

这是我的HTML字符串:

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

我希望所有样式都相同(斜体,粗体等),但我想将字体系列实现为Open Sans。所以,无论它的斜体在哪里,我都希望字体是Open-Sans Italics。我该如何实现?请帮忙。

3 个答案:

答案 0 :(得分:2)

尝试将NSAttributedString与NSHTMLTextDocumentType选项和.utf8字符串编码一起使用

斯威夫特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
}

答案 1 :(得分:2)

实现所需行为的一种方法是(复制并粘贴到游乐场)。

import PlaygroundSupport
import UIKit

func attributedString(fromHTML html: String, fontFamily: String) -> NSAttributedString? {
    let prefix = "<style>* { font-family: \(fontFamily) }</style>"
    return (prefix + html).data(using: .utf8).map {
        try! NSMutableAttributedString(
            data: $0,
            options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
            documentAttributes: nil
        )
    }
}

let attributedText = attributedString(fromHTML: "<i>Italics </i><b>Bold </b><u>Underline</u><blockquote>block quote<br></blockquote>", fontFamily: "Courier")

let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
label.backgroundColor = .white
label.attributedText = attributedText
PlaygroundPage.current.liveView = label

Example

答案 2 :(得分:1)

我必须添加自己的CSS。这解决了我的问题:

String DB_PATH = context.getDatabasePath(Constant.DATABASE_NAME).getPath();