これは、String
HTML 文字列を として返すために Swift で作成された拡張機能ですNSAttributedString
。
extension String {
func htmlAttributedString() -> NSAttributedString? {
guard let data = self.dataUsingEncoding(NSUTF16StringEncoding, allowLossyConversion: false) else { return nil }
guard let html = try? NSMutableAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) else { return nil }
return html
}
}
使用するには、
label.attributedText = "<b>Hello</b> \u{2022} babe".htmlAttributedString()
上記では、ユニコードを正しくレンダリングすることを示すために、意図的にユニコード \u2022 を追加しました。
些細なこと: 使用するデフォルトのエンコーディングNSAttributedString
はNSUTF16StringEncoding
(UTF8 ではありません!)。