Показ html и css файлов в textView

У меня есть файлы index.html и style.css. В этих файлах у меня только текст. И я хочу показать этот текст в моем textView. Если я использую этот код, я показываю текст из файла:

class ReadViewController: UIViewController {
    
    @IBOutlet weak var textView: UITextView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        do {
            guard let filePath = Bundle.main.path(forResource: "index", ofType: "html")
                else {
                    print ("File reading error")
                    return
            }

            let contents =  try String(contentsOfFile: filePath, encoding: .utf8)
            
            textView.attributedText = contents.htmlToAttributedString
        }
        catch {
            print ("File HTML error")
        }
    }
    
}

extension String {
    var htmlToAttributedString: NSAttributedString? {
        guard let data = data(using: .utf8) else { return nil }
        do {
            return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
        } catch {
            return nil
        }
    }
    var htmlToString: String {
        return htmlToAttributedString?.string ?? ""
    }
}

Но в этом случае мой текст отображается без жирного шрифта и других настроек стиля. Как это исправить? Как добавить файл style.css?


Ответы (1 шт):

Автор решения: Oleg Soloviev

введите сюда описание изображенияПопробуйте так:

import UIKit

class ViewController: UIViewController {

    let defaultHtmlStyle = """
    <style type=\"text/css\">
    body {font-family: \'Helvetica\'; font-weight: normal; font-style: normal; font-size: %.2fpt; color: #%@}
    </style>
    """

    @IBOutlet weak var textView: UITextView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        do {
            guard let filePath = Bundle.main.path(forResource: "index", ofType: "html")
                else {
                    print ("File reading error")
                    return
            }

            let contents =  try String(contentsOfFile: filePath, encoding: .utf8)
            let style = String(format: defaultHtmlStyle, 14.0, "000000")
            textView.attributedText = contents.htmlAttributed(using: style)
        }
        catch {
            print ("File HTML error")
        }
    }
}

extension String {
    func htmlAttributed(using style: String?) -> NSAttributedString? {
        let htmlCSSString = "\(style ?? "") \(self)"

        guard let data = htmlCSSString.data(using: String.Encoding.utf8) else {
            return nil
        }
        return try? NSAttributedString(data: data,
                                       options: [.documentType: NSAttributedString.DocumentType.html,
                                                 .characterEncoding: String.Encoding.utf8.rawValue],
                                       documentAttributes: nil)
    }
}
→ Ссылка