如何在swift中用nsattribute替换html标签?

时间:2017-07-05 07:07:57

标签: ios swift nsattributedstring

例如。用粗体字替换<strong>标记。这样它就可以作为属性文本应用于标签,文本字段或文本视图

3 个答案:

答案 0 :(得分:1)

extension NSAttributedString {

    func replaceHTMLTag(tag: String, withAttributes attributes: [String: AnyObject]) -> NSAttributedString {
        let openTag = "<\(tag)>"
        let closeTag = "</\(tag)>"

        let resultingText: NSMutableAttributedString = self.mutableCopy() as! NSMutableAttributedString
        while true {
            let plainString = resultingText.string as NSString
            let openTagRange = plainString.range(of: openTag)
            if openTagRange.length == 0 {
                break
            }

            let affectedLocation = openTagRange.location + openTagRange.length

            let searchRange = NSRange(location: affectedLocation, length: plainString.length - affectedLocation)

            let closeTagRange = plainString.range(of: closeTag, options: NSString.CompareOptions.init(rawValue: 0), range: searchRange)

            resultingText.setAttributes(attributes, range: NSRange(location: affectedLocation, length: closeTagRange.location - affectedLocation))
            resultingText.deleteCharacters(in: closeTagRange)
            resultingText.deleteCharacters(in: openTagRange)
        }
        return resultingText as NSAttributedString
    }
}

答案 1 :(得分:0)

您需要删除^和$ anchors。

^表示字符串的开头,$表示字符串的结尾(或行,取决于选项)。这就是你的第一个例子工作的原因:在第一个测试字符串中,字符串的开头实际上是你的模式,然后以它结束。

在第二个测试字符串中,模式位于字符串的中间,因此^ ...不能应用。如果您只是删除^,$将适用于第二次出现的注册号,输出将是我的汽车注册1 - DD11 AAA我的汽车注册2 - XX。

let myString = "my car reg 1 - DD11 AAA  my car reg 2 - AA22 BBB"
let regex = try! NSRegularExpression(pattern: "([A-HK-PRSVWY][A-HJ-PR-Y])\\s?([0][2-9]|[1-9][0-9])\\s?[A-HJ-PR-Z]{3}", options:        NSRegularExpressionOptions.CaseInsensitive)
let range = NSMakeRange(0, myString.characters.count)
let modString = regex.stringByReplacingMatchesInString(myString, options: [], range: range, withTemplate: "XX")
print(modString)
// Output: "my car reg 1 - XX  my car reg 2 - XX"

参考:https://stackoverflow.com/a/28503676/8169585

答案 2 :(得分:0)

试试此扩展程序。它会将HTML字符串转换为NSAttributtedString。我也应用0.75比率,因为默认转换增加了所有字体大小

extension String {
    func htmlAttributedString() -> NSAttributedString? {
        guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
        guard let html = try? NSMutableAttributedString(
            data: data,
            options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
            documentAttributes: nil) else { return nil }
        html.beginEditing()
        html.enumerateAttribute(NSFontAttributeName, in: NSMakeRange(0, html.length), options: .init(rawValue: 0)) {
            (value, range, stop) in
            if let font = value as? UIFont {
                let resizedFont = font.withSize(font.pointSize * 0.75)
                html.addAttribute(NSFontAttributeName,
                                         value: resizedFont,
                                         range: range)
            }
        }
        html.endEditing()
        return html
    }
}