ios 11 referencedString不适用于粗体文本

时间:2017-11-03 10:43:19

标签: ios swift3 ios11

我必须在数据库中保存htmlstring,它可能是粗体,斜体或下划线。 我使用下面的代码来获取我将保存在DB中的字符串。当我将这个保存的字符串从DB保存到我的IOS 10时它工作正常,但是在ios 11的情况下。我的文本没有被设置为风格(没有BOLD或斜体等)以前保存在DB中,但同样的文本工作在IOS 10上。

func htmlString() -> String? {
    let documentAttributes = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
    do {
      let htmlData = try self.data(from: NSMakeRange(0, self.length), documentAttributes:documentAttributes)
      if let htmlString = String(data:htmlData, encoding:String.Encoding.utf8) {
        return htmlString
      }
    }
    catch {}
    return nil
  }
}

1 个答案:

答案 0 :(得分:1)

我使用以下扩展函数将HTML html String自定义为NSAttributedString,它在iOS 10和11(Swift 3.2)上运行良好

在您的选项中也包含字符编码:

[NSCharacterEncodingDocumentAttribute : encoding.rawValue]

额外奖励 - 我发现HTML文本的样式很有用 - 如果您想更改字体和颜色,可以获得更多创意并自定义它。

extension String {
    public func htmlAttributedString(regularFont: UIFont, boldFont: UIFont, color: UIColor) -> NSAttributedString {
        let encoding = String.Encoding.utf8
        guard let descriptionData = data(using: encoding) else {
            return NSAttributedString()
        }
        let options: [String : Any] = [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute : encoding.rawValue]
        guard let attributedString = try? NSMutableAttributedString(data: descriptionData, options: options, documentAttributes: nil) else {
            return NSAttributedString()
        }

        let fullRange = NSMakeRange(0, attributedString.length)

        var regularRanges: [NSRange] = []
        var boldRanges: [NSRange] = []

        attributedString.beginEditing()
        attributedString.enumerateAttribute(NSFontAttributeName, in: fullRange, options: .longestEffectiveRangeNotRequired) { (value, range, stop) in
            guard let font = value as? UIFont else {
                return
            }
            if font.fontDescriptor.symbolicTraits.contains(.traitBold) {
                boldRanges.append(range)
            } else {
                regularRanges.append(range)
            }
        }

        for range in regularRanges {
            attributedString.addAttribute(NSFontAttributeName, value: regularFont, range: range)
        }

        for range in boldRanges {
            attributedString.addAttribute(NSFontAttributeName, value: boldFont, range: range)
        }

        attributedString.addAttribute(NSForegroundColorAttributeName, value: color, range: fullRange)

        attributedString.endEditing()

        return attributedString
    }
}