Dynamic Text Resizing in Swift

Jon Cardasis
2 min readSep 20, 2017

Oct 18, 2019 Update: You can now find a complete solution including an example app at https://github.com/joncardasis/FontFit.

Updated: May 26, 2018

Creating a great user experience lies in making every interaction feel nature and intended to the user. In a recent project, to make interactions feel more catered, I needed a UILabel to have it’s text scale to fit its bounds to the best extent that it can.

And so began my challenge.

There isn’t a simple cut-and-dry answer for this problem. Many developers run a while loop and keep upsizing the font size until it has the maximum fit. I wanted a faster method.

The implementation I ended up with was to leverage String’s boundingRect method. This method draws text with special attributes and will then return the size of the content. Perfect.

Using this I was able to create a base model of the text with a set font and then find a scalar between the results of boundingRect and the content size of the UILabel frame. Voila! I had a proper scaling font sizes.

Usage 📱

The implementation can be extended for any UI element (such as UITextField). A simple call to the new fitTextToBounds() function is all that is needed:

Simple as that.

Source Code 🚀

Update May 26, 2018: I’ve created a more robust solution for determining dynamic font sizing. The previous source code can still be found here.

Thanks for reading! Did you find this helpful in your project? Show your support 👏.

--

--