缩放后为不同标签设置相同的字体大小

缩放后为不同标签设置相同的字体大小

本文介绍了缩放后为不同标签设置相同的字体大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个有3个标签的应用程序.我正在使用标签自动缩小功能,以帮助使标签的字体大小适应设备.

I am making an app where I have 3 labels. I am using label auto-shrinking to help adapt the label's font size to the device.

这些标签彼此相邻,因此这意味着我希望它们具有相同的字体大小.当前发生的情况是(由于它们具有不同的文本量)最终缩小到了不同的字体大小.

These labels are right next to each other, and that therefore means that I want them to have them the same font size. What currently happens is (because they have different amounts of text) they end up shrinking to different font sizes.

有没有一种方法可以使缩放后的字体最小的标签成为所有其他标签的标准字体.

Is there a way to make it so that after scaling, the label with the smallest font size is the standard font for all of the other labels.

谢谢.

推荐答案

动态调整大小后,以编程方式更改UIlabel字体大小.请参见下面的示例.计算当前字体大小,字符串长度为&字体.然后获得最小字体大小并分别应用于每个UILabel

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 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
    }
}

故事板

输出

这篇关于缩放后为不同标签设置相同的字体大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 07:40