I\'m trying to have the UILabel shrink so that words don\'t truncate to the next line. Not just text truncating at the end of the text area.
If I have a box that is
SWIFT 3 translation of above extension. Works like a charm!
extension UILabel {
func fitToAvoidWordWrapping(){
// adjusts the font size to avoid long word to be wrapped
// get text as NSString
let text = self.text ?? ("" as NSString) as String
// get array of words separate by spaces
let words = text.components(separatedBy: " ")
// I will need to find the largest word and its width in points
var largestWord : NSString = ""
var largestWordWidth : CGFloat = 0
// iterate over the words to find the largest one
for word in words{
// get the width of the word given the actual font of the label
let wordSize = word.size(attributes: [NSFontAttributeName : self.font])
let wordWidth = wordSize.width
// check if this word is the largest one
if wordWidth > largestWordWidth{
largestWordWidth = wordWidth
largestWord = word as NSString
}
}
// now that I have the largest word, reduce the label's font size until it fits
while largestWordWidth > self.bounds.width && self.font.pointSize > 1{
// reduce font and update largest word's width
self.font = self.font.withSize(self.font.pointSize - 1)
let largestWordSize = largestWord.size(attributes: [NSFontAttributeName : self.font])
largestWordWidth = largestWordSize.width
}
}
}