Skip to content

Instantly share code, notes, and snippets.

@KelvinJin
Forked from chrislonge/AttributedHTMLFont.swift
Created October 18, 2017 04:31
Show Gist options
  • Save KelvinJin/a55a60475cba1e298c20b1fee4a55c57 to your computer and use it in GitHub Desktop.
Save KelvinJin/a55a60475cba1e298c20b1fee4a55c57 to your computer and use it in GitHub Desktop.
Attributed HTML With Custom Font Parsing (Playground)
import UIKit
import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
let containerView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 375.0, height: 667.0))
containerView.backgroundColor = UIColor.whiteColor()
XCPlaygroundPage.currentPage.liveView = containerView
var aboutTextView = UITextView(frame: CGRect(x: 12.0, y: 20.0, width: containerView.frame.size.width - 12.0, height: 200.0))
aboutTextView.textAlignment = .Left
aboutTextView.contentInset = UIEdgeInsets(top: -2, left: -4, bottom: 0, right: 0)
containerView.addSubview(aboutTextView)
let about: NSString = "<p><span><b>BOLD TEXT</b></span><br/></p><p><i>Italic text</i></p><p>normal text </p><ul><li>item 1</li><li>item 2</li><li>item 3</li></ul><ol><li>one</li><li>two </li><li>three</li></ol><p><br/></p>"
let regAbout: NSString = "Regular text with no formatting or rich text"
// Setup Custom Fonts
let proximaNovaRegURL = NSBundle.mainBundle().URLForResource("ProximaNova-Reg", withExtension: "otf")
let proximaNovaBoldURL = NSBundle.mainBundle().URLForResource("ProximaNova-Bold", withExtension: "otf")
let proximaNovaRegItURL = NSBundle.mainBundle().URLForResource("ProximaNova-RegIt", withExtension: "otf")
CTFontManagerRegisterFontsForURL(proximaNovaRegURL!, CTFontManagerScope.Process, nil)
CTFontManagerRegisterFontsForURL(proximaNovaBoldURL!, CTFontManagerScope.Process, nil)
CTFontManagerRegisterFontsForURL(proximaNovaRegItURL!, CTFontManagerScope.Process, nil)
let fonts = UIFont.fontNamesForFamilyName("Proxima Nova")
let proximaNovaReg = UIFont(name: "ProximaNova-Regular", size: 12.0)
// Approach 1
let aboutFontAppended = about.stringByAppendingString("<style>body{font-family: Proxima Nova; font-size:15px;}</style>")
let aboutData = aboutFontAppended.dataUsingEncoding(NSUTF8StringEncoding)
let options = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
do {
let attributedStr = try NSAttributedString(data: aboutData!, options: options, documentAttributes: nil)
} catch {
print(error)
}
/// Approach 2 - I like this way!
let about2 = "<span style=\"font-family: Proxima Nova; font-size: 15.0\">\(about)</span>"
let aboutData2 = about2.dataUsingEncoding(NSUTF8StringEncoding)
do {
let attributedStr = try NSMutableAttributedString(data: aboutData2!, options: options, documentAttributes: nil)
aboutTextView.attributedText = attributedStr
aboutTextView.sizeToFit()
print(aboutTextView.frame.size.height)
} catch {
print(error)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment