I have two UILabels which I need to adjust the font size in order to properly fit the text (namely in smaller, older devices).
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).
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.
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. 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:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.