简体   繁体   English

调整UILabel字体大小,而不使用.adjustsFontForContentSizeCategory

[英]Adjust UILabel font size without .adjustsFontForContentSizeCategory

I have two UILabels which I need to adjust the font size in order to properly fit the text (namely in smaller, older devices). 我有两个UILabel,它们需要调整字体大小以适合文本(即在较小的旧设备中)。

This would be easily solved with the .adjustsFontSizeToFitWidth property but the thing is that, as both UILabels are near one another and convey similar information, I want them to have the same font size (and adjustsFontSizeToFitWidth will adjust them independently). 使用.adjustsFontSizeToFitWidth属性可以轻松解决此问题,但事实是,由于两个UILabels彼此靠近并传达相似的信息,因此我希望它们具有相同的字体大小(而adjustsFontSizeToFitWidth可以独立调整它们)。

So, what I was thinking to do would be to, somehow (this is where I need help) calculate what would the font size need to be for both the labels and use the smallest on both. 因此,我当时想做的就是以某种方式(这是我需要帮助的地方)计算两个标签的字体大小,并在两个标签上使用最小的字体。

图片

Any ideas on how to do this? 有关如何执行此操作的任何想法? Both labels are multiline (2 lines) and they always have the same size. 两个标签都是多行(2行),并且它们始终具有相同的大小。

Thanks in advance. 提前致谢。

What you could do have the .adjustsFontSizeToFitWidth property true, get font of smallest one, then compare the two widths and set the width of both to the smallest one. 您可以将.adjustsFontSizeToFitWidth属性设置为true,获得最小字体,然后比较两个宽度,并将两者的宽度都设置为最小。 Example in pseudo code: 伪代码示例:

.adjustsFontSizeToFitWidth = true
var fontSizeOne = labelOne.fontSize
var fontSizeTwo = labelTwo.fontSize

if(fontSizeOne < fontSizeTwo)
  {
    labelTwo.fontSize = labelOne.fontSize
  }
else
  {
    labelOne.fontSize = labelTwo.fontSize
  }

You could make @Will's answer ever shorter using the min function: 您可以使用min函数使@Will的答案变得更短:

    labelOne.adjustsFontSizeToFitWidth = true 
    labelTwo.adjustFontSizeToFitWidth = true

    var fontSizeOne = labelOne.font.pointSize
    var fontSizeTwo = labelTwo.font.pointSize

    var min = min(fontSizeOne, fontSizeTwo)
    labelOne.font = UIFont.systemFont(ofSize: min))
    labelTwo.font = labelOne.font

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM