Swift UILebelの指定複数箇所に色を付ける その2:UILabelにHTMLを反映
実現したい事
その2:UILabelにHTMLを反映
HTMLを反映:「1:00 Paris Saint-Germain – FC Nantes」
htmlTextにHTML文字列が格納されている前提。
guard let data = htmlText.data(using: .utf8) else {
return
}
do {
let option: [NSAttributedString.DocumentReadingOptionKey: Any] = [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue]
let attrString = try NSMutableAttributedString(data: data, options: option, documentAttributes: nil)
label.attributedText = attrString
label.font = UIFont.systemFont(ofSize: 9, weight: .medium)
label.lineBreakMode = .byCharWrapping
} catch {
print(error.localizedDescription)
}
- NSMutableAttributedStringを使用
- UILabel.attributedTextに設定
- UILabel.fontやlineBreakModeは文字列設定後に設定
事前にStoryboardに設定されていても反映されない








