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

前端 未结 14 739
独厮守ぢ
独厮守ぢ 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:14

    Here's a Swift extension for UILabel. It runs a binary search algorithm to resize the font and bounds of the label, and is tested to work for iOS 12.

    USAGE: Resizes the font to fit a size of 100x100 (accurate within 1.0 font point) and aligns it to top.

    let adjustedSize = 

    Copy/Paste the following into your file:

    extension UILabel {
        @discardableResult func fitFontForSize(_ constrainedSize: CGSize,
                                               maxFontSize: CGFloat = 100,
                                               minFontSize: CGFloat = 5,
                                               accuracy: CGFloat = 1) -> CGSize {
            assert(maxFontSize > minFontSize)
    
            var minFontSize = minFontSize
            var maxFontSize = maxFontSize
            var fittingSize = constrainedSize
    
            while maxFontSize - minFontSize > accuracy {
                let midFontSize: CGFloat = ((minFontSize + maxFontSize) / 2)
                font = font.withSize(midFontSize)
                fittingSize = sizeThatFits(constrainedSize)
                if fittingSize.height <= constrainedSize.height
                    && fittingSize.width <= constrainedSize.width {
                    minFontSize = midFontSize
                } else {
                    maxFontSize = midFontSize
                }
            }
    
            return fittingSize
        }
    } 
    

    This function will not change the label size, only the font property is affected. You can use the returned size value to adjust the layout of the label.

提交回复
热议问题