Skip to content

Instantly share code, notes, and snippets.

@fernandomatal
Last active November 7, 2016 10:38
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 fernandomatal/ce803be907fef84824e2ad1c4e4714b4 to your computer and use it in GitHub Desktop.
Save fernandomatal/ce803be907fef84824e2ad1c4e4714b4 to your computer and use it in GitHub Desktop.
String extension that returns the best font size to fit certain size
extension String {
func fontSizeThatFitsWidth(size: CGSize, font: UIFont) -> CGFloat {
let testString = self as NSString
var fontSize: CGFloat = 100
let minFontSize: CGFloat = 5
while fontSize > minFontSize {
let testFont = font.fontWithSize(fontSize)
let textSize = testString.sizeWithAttributes([NSFontAttributeName : testFont])
if textSize.width > size.width {
fontSize -= 2
} else {
break
}
}
return fontSize
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment