Skip to content

Instantly share code, notes, and snippets.

@S1U
Last active April 7, 2016 09:27
Show Gist options
  • Save S1U/4b1c52714b31047461862717fd9dcc1f to your computer and use it in GitHub Desktop.
Save S1U/4b1c52714b31047461862717fd9dcc1f to your computer and use it in GitHub Desktop.
Adaptive font fits to height of UILabel, UITextView
// Inspired from
// http://stackoverflow.com/a/26221732/2438676
// http://derekneely.com/tag/resize-text/
// http://stackoverflow.com/a/27115350/2438676
import UIKit
extension UIFont {
class func adaptiveFontWithName(fontName: String, label: UILabel, minSize: CGFloat = 9, maxSize: CGFloat = 999) -> UIFont! {
var tempFont: UIFont
var tempMax: CGFloat = maxSize
var tempMin: CGFloat = minSize
while (ceil(tempMin) != ceil(tempMax)) {
let testedSize = (tempMax + tempMin) / 2
tempFont = UIFont(name:fontName, size:testedSize)!
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.hyphenationFactor = 1.0
let attributedString = NSAttributedString(string: label.text!, attributes: [NSFontAttributeName: tempFont, NSParagraphStyleAttributeName: paragraphStyle])
let textFrame = attributedString.boundingRectWithSize(CGSize(width: label.bounds.size.width, height: CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin , context: nil)
let difference = label.frame.height - textFrame.height
// print("\(tempMin)-\(tempMax) - tested : \(testedSize) --> difference : \(difference)")
if (difference > 0) {
tempMin = testedSize
} else {
tempMax = testedSize
}
}
// returning the size -1 (to have enought space right and left)
return UIFont(name: fontName, size: tempMin)
}
class func simpleAdaptiveFontWithName(fontName: String, textView: UITextView, fontSize: CGFloat = 24) -> UIFont! {
textView.font = UIFont(name: fontName, size: fontSize)
var adaptiveFontSize = fontSize
while (textView.contentSize.height < textView.frame.size.height) {
adaptiveFontSize += 1
textView.font = UIFont(name: fontName, size: adaptiveFontSize)
}
return textView.font
}
class func adaptiveFontWithName(fontName: String, textView: UITextView, fontSize: CGFloat = 24) -> UIFont!{
textView.font = UIFont(name: fontName, size: fontSize)!
let textViewSize = textView.frame.size;
let fixedWidth = textViewSize.width;
let adaptiveTextViewSize = textView.sizeThatFits(CGSizeMake(fixedWidth, CGFloat(MAXFLOAT)));
var adaptiveFontSize = fontSize
if (adaptiveTextViewSize.height > textViewSize.height) {
while (textView.sizeThatFits(CGSizeMake(fixedWidth, CGFloat(MAXFLOAT))).height > textViewSize.height) {
adaptiveFontSize -= 1
textView.font = textView.font!.fontWithSize(adaptiveFontSize)
}
} else {
while (textView.sizeThatFits(CGSizeMake(fixedWidth, CGFloat(MAXFLOAT))).height < textViewSize.height) {
adaptiveFontSize += 1
textView.font = textView.font!.fontWithSize(adaptiveFontSize)
}
}
return textView.font
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment