Created
April 4, 2016 15:04
-
-
Save mmcbrear/3763d0b0d9849e65edd5a4666eb94318 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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