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

前端 未结 14 770
独厮守ぢ
独厮守ぢ 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 07:27

    Swift 3 "binary search solution" based on this answer with minor improvements. Sample is in context of UITextView subclass:

    func binarySearchOptimalFontSize(min: Int, max: Int) -> Int {
        let middleSize = (min + max) / 2
    
        if min > max {
            return middleSize
        }
    
        let middleFont = UIFont(name: font!.fontName, size: CGFloat(middleSize))!
    
        let attributes = [NSFontAttributeName : middleFont]
        let attributedString = NSAttributedString(string: text, attributes: attributes)
    
        let size = CGSize(width: bounds.width, height: .greatestFiniteMagnitude)
        let options: NSStringDrawingOptions = [.usesLineFragmentOrigin, .usesFontLeading]
        let textSize = attributedString.boundingRect(with: size, options: options, context: nil)
    
        if textSize.size.equalTo(bounds.size) {
            return middleSize
        } else if (textSize.height > bounds.size.height || textSize.width > bounds.size.width) {
            return binarySearchOptimalFontSize(min: min, max: middleSize - 1)
        } else {
            return binarySearchOptimalFontSize(min: middleSize + 1, max: max)
        }
    }
    

    I hope that helps someone.

提交回复
热议问题