Last active
November 7, 2016 10:38
-
-
Save fernandomatal/ce803be907fef84824e2ad1c4e4714b4 to your computer and use it in GitHub Desktop.
String extension that returns the best font size to fit certain 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
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