私は自分のネイティブUILabelでレンダリングしたいいくつかのHTMLコンテンツを持っていますが、それに加えてカスタムフォントをそのUILabelに追加する必要があります。私はNSAttributedStringを使ってこれを行い、次のコードを使用してUILabelのHTMLコンテンツをレンダリングしています。HTMLにレンダリングされたUILabelスウィフトにフォント属性を追加する
func htmlAttributedString() -> NSAttributedString? {
guard let data = self.data(using: .utf16, allowLossyConversion: false) else {
return nil
}
guard let html = try? NSMutableAttributedString(
data: data,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil) else { return nil }
let attributes = [
NSForegroundColorAttributeName: UIColor.lightGray,
NSFontAttributeName : UIFont.systemFont(ofSize: 12)
]
html.setAttributes(attributes, range: NSRange(0..<html.length))
return html
}
var str = "Here is the <bold>string</bold> that i want to be bold.
messageLabel.attributedText = str.htmlAttributedString()
ここでの問題は、HTMLで表示される属性付き文字列にフォント属性を適用する場合です。太字のようなHTML書式はすべて失われます。
だから私は、HTML上のいくつかの選択されたフォントが属性付き文字列
https://stackoverflow.com/a/44435915/5362916この1 –
使用して、このリンクをチェックします。https://stackoverflow.com/questions/28496093/making-text-bold-using-attributed-string -in-swift – ashwini
@UmaMadhaviあなたのリンクは私のために働いた。ありがとう – Madu