Skip to content

Instantly share code, notes, and snippets.

@grigorevp
Last active October 13, 2021 22:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grigorevp/5326348a8b373ea5e3d7327fb3f3afa8 to your computer and use it in GitHub Desktop.
Save grigorevp/5326348a8b373ea5e3d7327fb3f3afa8 to your computer and use it in GitHub Desktop.
An extension to UIFont returning UIFont based on pixel size
// This code was reshaped from Joel Fischer's answer from here:
// https://stackoverflow.com/questions/8812192/how-to-set-font-size-to-fill-uilabel-height/17622215#17622215
import UIKit
extension UIFont {
static func getFont(name: String, maxSize: CGFloat, heightToFit: CGFloat) -> UIFont {
let testString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
var font: UIFont
var tempMax: CGFloat = maxSize
var tempMin: CGFloat = 1
while (ceil(tempMin) != ceil(tempMax)){
let testedSize = (tempMax + tempMin) / 2
font = UIFont(name: name, size: testedSize) ?? UIFont.systemFont(ofSize: testedSize)
let attributedString = NSAttributedString(string: testString, attributes: [NSAttributedString.Key.font: font])
let textFrame = attributedString.boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude), options: NSStringDrawingOptions.usesLineFragmentOrigin , context: nil)
let difference = heightToFit - textFrame.height
if(difference > 0){
tempMin = testedSize
}else{
tempMax = testedSize
}
}
return UIFont(name: name, size: tempMin - 1) ?? UIFont.systemFont(ofSize: tempMin - 1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment