iOS UILabel autoshrink so word doesn't truncate to two lines

前端 未结 4 376
陌清茗
陌清茗 2020-12-11 06:35

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

4条回答
  •  自闭症患者
    2020-12-11 07:35

    I made a Swift extension of UILabel. Just call the method to the label after bounds and text are set.

    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
    
        // get array of words separate by spaces
        let words = text.componentsSeparatedByString(" ") as! [NSString]
    
        // 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.sizeWithAttributes([NSFontAttributeName : self.font])
            let wordWidth = wordSize.width
    
            // check if this word is the largest one
            if wordWidth > largestWordWidth{
            largestWordWidth = wordWidth
            largestWord = word
            }
        }
    
        // 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.fontWithSize(self.font.pointSize - 1)
            let largestWordSize = largestWord.sizeWithAttributes([NSFontAttributeName : self.font])
            largestWordWidth = largestWordSize.width
        }
    }
    } 
    

提交回复
热议问题