Autoshrink on a UILabel with multiple lines

前端 未结 17 2053
醉梦人生
醉梦人生 2020-11-28 21:31

Is it possible to use the autoshrink property in conjunction on multiple lines on a UILabel? for example, the large text size possible on 2 available lines.

17条回答
  •  醉酒成梦
    2020-11-28 22:07

    Try this:

    Either subclass UILabel or call adjustFontSize method after setting the text property on a label

    override var text : String? { didSet { self.adjustFontSize() } }
    
    func adjustFontSize()
    {
        var lineCount = self.string.components(separatedBy: "\n").count - 1
        var textArray = self.string.components(separatedBy: " ")
        var wordsToCompare = 1
        while(textArray.count > 0)
        {
            let words = textArray.first(n: wordsToCompare).joined(separator: " ")
            let wordsWidth = words.widthForHeight(0, font: self.font)
            if(wordsWidth > self.frame.width)
            {
                textArray.removeFirst(wordsToCompare)
                lineCount += 1
                wordsToCompare = 1
            }
            else if(wordsToCompare > textArray.count)
            {
                break
            }
            else
            {
                wordsToCompare += 1
            }
        }
        self.numberOfLines = lineCount + 1
    }
    

提交回复
热议问题