How to adjust font size of label to fit the rectangle?

前端 未结 14 788
独厮守ぢ
独厮守ぢ 2020-11-28 07:00

Yeah, there\'s this cool myLabel.adjustsFontSizeToFitWidth = YES; property. But as soon as the label has two lines or more, it won\'t resize the text to anythin

14条回答
  •  北荒
    北荒 (楼主)
    2020-11-28 07:00

    Here's Swift version according to @NielsCastle answer, using binary search

    extension UILabel{
    
        func adjustFontSizeToFitRect(rect : CGRect){
    
            if text == nil{
                return
            }
    
            frame = rect
    
            let maxFontSize: CGFloat = 100.0
            let minFontSize: CGFloat = 5.0
    
            var q = Int(maxFontSize)
            var p = Int(minFontSize)
    
            let constraintSize = CGSize(width: rect.width, height: CGFloat.max)
    
            while(p <= q){
                let currentSize = (p + q) / 2
                font = font.fontWithSize( CGFloat(currentSize) )
                let text = NSAttributedString(string: self.text!, attributes: [NSFontAttributeName:font])
                let textRect = text.boundingRectWithSize(constraintSize, options: .UsesLineFragmentOrigin, context: nil)
    
                let labelSize = textRect.size
    
                if labelSize.height < frame.height && labelSize.height >= frame.height-10 && labelSize.width < frame.width && labelSize.width >= frame.width-10 {
                    break
                }else if labelSize.height > frame.height || labelSize.width > frame.width{
                    q = currentSize - 1
                }else{
                    p = currentSize + 1
                }
            }
    
        }
    }
    

    Usage

    label.adjustFontSizeToFitRect(rect)
    

    often just

    label.adjustFontSizeToFitRect(rect.frame)
    

提交回复
热议问题