Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 views
in Technique[技术] by (71.8m points)

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

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!!! 
>(String(describing: attr))<
")
    }
    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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...