Setting the same font size for different labels AFTER scaling

China☆狼群 提交于 2019-12-04 07:18:02

Programatically change UIlabel font size after dynamic resizing. See the example below. Calculate current font size with length of string & font. And then get minimum font size and apply separately for each UILabel

override func viewWillAppear(_ animated: Bool) {
    let fontSize1 = self.label1.getFontSizeForLabel()
    let fontSize2 = self.label2.getFontSizeForLabel()
    let fontSize3 = self.label3.getFontSizeForLabel()

    let smallestFontSize = min(min(fontSize1, fontSize2), fontSize3)

    self.label1.font = self.label1.font.withSize(smallestFontSize)
    self.label2.font = self.label2.font.withSize(smallestFontSize)
    self.label3.font = self.label3.font.withSize(smallestFontSize)

    self.label1.adjustsFontSizeToFitWidth = false
    self.label2.adjustsFontSizeToFitWidth = false
    self.label3.adjustsFontSizeToFitWidth = false
}

UILabel Extension

extension UILabel {
    func getFontSizeForLabel() -> CGFloat {
        let text: NSMutableAttributedString = NSMutableAttributedString(attributedString: self.attributedText!)
        text.setAttributes([NSAttributedStringKey.font: self.font], range: NSMakeRange(0, text.length))
        let context: NSStringDrawingContext = NSStringDrawingContext()
        context.minimumScaleFactor = self.minimumScaleFactor
        text.boundingRect(with: self.frame.size, options: NSStringDrawingOptions.usesLineFragmentOrigin, context: context)
        let adjustedFontSize: CGFloat = self.font.pointSize * context.actualScaleFactor
        return adjustedFontSize
    }
}

Storyboard

Output

This is a duplicate of the question, there I answered how to solve this problem: https://stackoverflow.com/a/58376331/9024807

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!