create an attributed string out of plain (Android formatted) text in swift for iOS

♀尐吖头ヾ 提交于 2019-12-03 08:15:49
Martin R

Regarding your first method with NSAttributedString:

This gives (now updated for Swift 2):

func convertText(inputText: String) -> NSAttributedString {

    var html = inputText

    // Replace newline character by HTML line break
    while let range = html.rangeOfString("\n") {
        html.replaceRange(range, with: "<br />")
    }

    // Embed in a <span> for font attributes:
    html = "<span style=\"font-family: Helvetica; font-size:14pt;\">" + html + "</span>"

    let data = html.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!
    let attrStr = try? NSAttributedString(
        data: data,
        options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
        documentAttributes: nil)
    return attrStr!
}

Regarding your second method:

There are two different rangeOfString() methods, one for (Swift) String and one for (Foundation) NSString. The String method returns a Range<String.Index> and the NSString method returns an NSRange.

Converting between these two is possible but complicated. The reason is that in a String each "extended grapheme cluster" counts as one character, whereas in NSString each UTF-16 unit is counted. An extended grapheme cluster can be one or more UTF-16 unit ("😄" is two UTF-16 units, "🇩🇪" is four).

The addAttribute() method accepts only an NSRange. The easiest method to solve this problem is to convert the Swift string to NSString and work with NSRange only. Then your method could look like this:

func convertText(inputText: String) -> NSAttributedString {

    let attrString = NSMutableAttributedString(string: inputText)
    let boldFont = UIFont(name: "Helvetica-Bold", size: 14.0)!

    var r1 = (attrString.string as NSString).rangeOfString("<b>")
    while r1.location != NSNotFound {
        let r2 = (attrString.string as NSString).rangeOfString("</b>")
        if r2.location != NSNotFound  && r2.location > r1.location {
            let r3 = NSMakeRange(r1.location + r1.length, r2.location - r1.location - r1.length)
            attrString.addAttribute(NSFontAttributeName, value: boldFont, range: r3)
            attrString.replaceCharactersInRange(r2, withString: "")
            attrString.replaceCharactersInRange(r1, withString: "")
        } else {
            break
        }
        r1 = (attrString.string as NSString).rangeOfString("<b>")
    }

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