1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

HtmlタグでStringを装飾する方法

Last updated at Posted at 2020-09-06
  • htmlタグをStringで書いて
  • そのStringをData変換
  • NSMutableAttributedString(data:options:documentAttributes)で装飾する
  • options に documentType.html を指定
let str = "<i>testText</i>"
let stringWithBaseFont = NSString(format:"<span style=\"font-family: '-apple-system', 'HelveticaNeue'; font-size: \(22)\">%@</span>" as NSString, str)

stringWithBaseFont.data(using: String.Encoding.unicode.rawValue, allowLossyConversion: true)!

if let attributedString = try? NSMutableAttributedString(
    data: stringWithBaseFont.data(using: String.Encoding.unicode.rawValue, allowLossyConversion: true)!,
    options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue],
    documentAttributes: nil) {
    attributedString.addAttribute(.foregroundColor, value: UIColor.red, range: NSRange(location: 0, length: attributedString.length))
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?