I have a UITextField
for which I’ve set autoAdjustFontSizeToFitWidth
to true
and minimumFontSize
to 0
. The problem is the setting shrinks the text noticeably sooner than it really should. For example, here is an image of a UITextField
with the above settings:
The green is the background color of the UITextField
. In this example, the text has not shrunk yet, but no matter what I type as the next character the text field always begins shrinking; despite clearly being enough room on the left side for a few more characters. Here is another image with additional characters entered:
As you can see, there is a relatively large area on the left side that the text field won’t place text in when auto adjusting. This is for a right aligned text field. The same can be said of center aligned text fields as well, where there is space on the left and right that seems as if an auto adjusting text field won’t place text inside.
How do I get it so that auto adjusting text fields use the entire available space?
2
Answers
Update:
You can do the text calculations and font resizing manually. By doing so you will avoid hacks and future compatibility issues.
A simple implementation looks like this:
Interestingly the actual relationship between text rect and font size is non-linear and non-trivial. So I added multiple iteration steps to approximate the correct size. I chose a maximum of 10 iterations to avoid infinite loops on very small sizes and rounding errors.
Original Answer:
There has always been some magic around
UITextField
andadjustsFontSizeToFitWidth
. See for example this post from 2015 about how the initial font size affects the minimum font size:https://stackoverflow.com/a/30881385/921573
In my tests, setting the minimum font size in IB to 0 just gets ignored – in order so see the shrinking effect it has to be a small value like 1.
Setting it in code to 0 works fine.
So I think it is safe to say that
UITextField
might be considered historically buggy when it comes toadjustsFontSizeToFitWidth
.That being said, I found a workaround for you:
This custom text field uses countermagic to mitigate the issue.
You may have to play with the magicNumber according to your font or dimensions or device. For me 15 works ok:
This works for me and the
textField.textAlignment
is set to.right
(it will depend on how many characters you put in the textField though) :