Skip to content

Instantly share code, notes, and snippets.

@mmcbrear
Created April 4, 2016 15:04
Show Gist options
  • Save mmcbrear/3763d0b0d9849e65edd5a4666eb94318 to your computer and use it in GitHub Desktop.
Save mmcbrear/3763d0b0d9849e65edd5a4666eb94318 to your computer and use it in GitHub Desktop.
import Foundation
import UIKit
extension UILabel {
func resizeFontToFitHeight() {
guard let text = text else { return }
let labelHeight = CGRectGetHeight(frame)
var stringHeight = NSString(string: text).sizeWithAttributes([NSFontAttributeName : font.fontWithSize(font.pointSize)]).height
var fontSize = font.pointSize
while stringHeight < labelHeight {
fontSize++
font = font.fontWithSize(fontSize)
stringHeight = NSString(string: text).boundingRectWithSize(frame.size, options: .UsesFontLeading, attributes: [NSFontAttributeName : font], context: nil).size.height
}
font = font.fontWithSize(fontSize)
}
func textSize() -> CGSize {
guard let text = text else { return frame.size }
let attributedText = NSAttributedString(string: text, attributes: [NSFontAttributeName: font])
let rect = CGRectIntegral(attributedText.boundingRectWithSize(CGSizeMake(frame.size.width, CGFloat(MAXFLOAT)), options: [.UsesLineFragmentOrigin, .UsesFontLeading], context:nil))
return rect.size
}
func lineCountForLabel() -> Int {
let labelWidth = frame.size.width
var lineCount = 0
let textSize = CGSizeMake(labelWidth, CGFloat(MAXFLOAT))
let rHeight = lroundf(Float(sizeThatFits(textSize).height))
let charSize = lroundf(Float(font.leading))
lineCount = Int(rHeight/charSize)
return lineCount
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment