Last active
October 13, 2021 22:11
-
-
Save grigorevp/5326348a8b373ea5e3d7327fb3f3afa8 to your computer and use it in GitHub Desktop.
An extension to UIFont returning UIFont based on pixel size
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
// 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