HTML to attributed string to HTML increase font size for random text

痴心易碎 提交于 2019-12-11 17:52:42

问题


This is my HTML sample string.

"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\"><html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"><meta http-equiv=\"Content-Style-Type\" content=\"text/css\"><title></title><meta name=\"Generator\" content=\"Cocoa HTML Writer\"><style type=\"text/css\">p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; line-height: 40.0px; font: 33.2px '.SF UI Text'; color: #000000; -webkit-text-stroke: #000000}span.s1 {font-family: '.SFUIText'; font-weight: normal; font-style: normal; font-size: 33.19pt; font-kerning: none}</style></head><body><p class=\"p1\"><span class=\"s1\">123</span></p></body></html>"

Here are two functions to converting from HTML to attribute string to HTML for dealing server size too.

Attribute string to HTML:

func attributeToHTML(_ attr: NSAttributedString) -> String {

    var resultHtmlText = ""
    do {

        let r = NSRange(location: 0, length: (attr.length))
        let att = [NSAttributedString.DocumentAttributeKey.documentType: NSAttributedString.DocumentType.html]
        let d = try attr.data(from: r, documentAttributes: att)

        if let h = String(data: d, encoding: .utf8) {
            resultHtmlText = h
        }
    }
    catch {
        print("utterly failed to convert to html!!! \n>\(String(describing: attr))<\n")
    }
    return resultHtmlText
}

HTML to Attributed string:

func htmlToAttribute(_ string: String) -> NSAttributedString {
    let htmlString = string
    var result = NSAttributedString()
    do {
        let options = [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html]
        let str = try NSAttributedString(data: htmlString.data(using: String.Encoding.unicode, allowLossyConversion: true)!, options: options, documentAttributes: nil)
        result = attributedString
    } catch {
        print(error)
    }

    return result
}

When I convert HTML string to attributed string it increases the font size, and working perfect with attributed string to HTML conversion.

By enumerating objects I can edit font size too, but its dynamic content any type of HTML string get in response. So this is not solutions.

Please suggest the way how to deal with HTML content in UITextview for editing and storing in server.

来源:https://stackoverflow.com/questions/51560409/html-to-attributed-string-to-html-increase-font-size-for-random-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!