0

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.

image

Any ideas on how to do this? Both labels are multiline (2 lines) and they always have the same size.

Thanks in advance.

Adil Soomro
  • 37,609
  • 9
  • 103
  • 153

2 Answers2

0

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
  }
Will Boland
  • 146
  • 2
  • 13
  • Initially I thought of this but it looks like that the fontSize property remains the same despite any change to the font size! – Luis Machado Jan 20 '17 at 15:39
0

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
Eric
  • 1,210
  • 8
  • 25
  • 1st of all thanks for the reply Eric! However this didn't work. As I suspected the pointSize remains the same despite the visual change of the size. – Luis Machado Jan 20 '17 at 16:57
  • fontSizeOne: 20.0 fontSizeTwo: 20.0 – Luis Machado Jan 20 '17 at 17:01
  • It seems to be very hard to get the actual font size, maybe [this stack-overflow post](http://stackoverflow.com/questions/34622503/when-do-adjustsfontsizetofitwidth-or-boundingrectwithsize-change-the-context-act) can help you? – Eric Jan 22 '17 at 17:09