Skip to content

Instantly share code, notes, and snippets.

@r-aamir
Created June 1, 2019 11:24
Show Gist options
  • Save r-aamir/0f92e2bae59ab07ad3422a3a4f8d8d19 to your computer and use it in GitHub Desktop.
Save r-aamir/0f92e2bae59ab07ad3422a3a4f8d8d19 to your computer and use it in GitHub Desktop.
NSAttributedString from HTML: Add different font sizes for title and description https://stackoverflow.com/questions/56404650
import UIKit
import PlaygroundSupport
extension UIFont {
func cssStyle(selector: String, otherStyles styles: String = "") -> String {
return "\(selector){font-family:\(fontName);font-size:\(Int(pointSize));\(styles)}"
}
}
let text = "<span class=heading>Stackoverflow</span> is launched in 2008, it currently has 231,083 Swift questions out of 52,499,188 total."
let textView = UITextView(frame: CGRect(x: 0, y: 0, width: 320, height: 320))
let headerStyle = UIFont(name: "ArialRoundedMTBold", size: 30)!.cssStyle(selector: ".heading", otherStyles: "color:#000")
let commonStyle = UIFont(name: "ArialMT", size: 22)!.cssStyle(selector: "*", otherStyles: "color:#666")
let htmlData = Data("<style>\(commonStyle)\(headerStyle)</style>\(text)".utf8)
textView.attributedText = try? NSAttributedString(data: htmlData, options: [
.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue
], documentAttributes: nil)
PlaygroundPage.current.liveView = textView
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment