Skip to content

Instantly share code, notes, and snippets.

@artemisia-absynthium
Created July 25, 2017 13:43
Show Gist options
  • Save artemisia-absynthium/71d21883a937b45a733b191b0afb21f1 to your computer and use it in GitHub Desktop.
Save artemisia-absynthium/71d21883a937b45a733b191b0afb21f1 to your computer and use it in GitHub Desktop.
Useful iOS extensions
extension UIColor {
func toHex() -> String {
var r:CGFloat = 0
var g:CGFloat = 0
var b:CGFloat = 0
var a:CGFloat = 0
getRed(&r, green: &g, blue: &b, alpha: &a)
let rgb:Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0
return String(format:"#%06x", rgb)
}
}
extension UITextView {
func from(html: String) throws -> NSAttributedString {
let htmlString = "<body>"
.appending(html)
.appending("</body><style>body{font-family:'")
.appending(font!.familyName)
.appending("'; font-size:")
.appending(font!.pointSize.description)
.appending("; color:")
.appending(textColor?.toHex() ?? #colorLiteral(red: 0.2901960784, green: 0.2901960784, blue: 0.2901960784, alpha: 1).toHex())
.appending(";}</style>")
return try NSAttributedString.init(data: (htmlString.data(using: .unicode, allowLossyConversion: false))!, options: [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType], documentAttributes: nil)
}
func lines() -> Int {
var numberOfLines = 0
var index = 0
let numberOfGlyphs = layoutManager.numberOfGlyphs
var lineRange = NSRange()
while index < numberOfGlyphs {
layoutManager.lineFragmentRect(forGlyphAt: index, effectiveRange: &lineRange)
index = NSMaxRange(lineRange)
numberOfLines += 1
}
return numberOfLines
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment