Working with icon fonts in iOS. Code example in Swift 3.
When I just have started iOS development there was no such thing as retina display. Everything was pretty easy back then. You just recive all assets from your fellow designer, copy them into Resources folder in XCode project and that’s all. The only thing we have to worry about was color of icons for different states.
But then iPhone 4 with retina display was introduced and designers had to draw every icon twice. At first this weird “@2x” syntax was confusing but we got used to it. With iPhone 6 Plus we had another screen resolution and “@3x” addition to our icons. And nowadays if you do not support first iPad mini or iPad 2 there is no need in original “@1x” images so you are using “@2x” as default ones. Wonder how new iOS developers feels about this…
It gets even worse if you need exact same icons but in different sizes. So you having this “play-icon-small.png” and “play-icon-big.png” files. Do not forget about states so what you really having is “play-icon-small-enabled.png” and “play-icon-small-disable.png” … well, you get the point.
And after all this years there are no actual support for vector graphics on iOS. This is obvious solution for all problems mentioned above but it’s still not here.
But don’t cry. Somebody came up with a simple yet elegant idea of using custom fonts for iOS icons and images. It solves all the problems mentioned above and it is really lightweight solution. The only problem with this — you don’t have system support and you have to do all the things by yourself.
If you are working with graphical designer he or she probably already knows how to create icon font for you. If not you can check something like IconMoon. It will not only generate font itself but also will give you a demo .html file with hex codes for each symbol.
Let’s get into some work.
First of all you need to add .ttf file into your XCode project and then add its name into your Info.plist file like this
After that you need to load this font in order to use it. It could be done like this:
We can wrap our font in enum like this:
So all we have to do now is create a method that load each individual symbol into String. Here is an example of this:
After that you just need to create some public functions that suits your case. I’ve made samething like this:
This is it. You may want to add another level of abstraction, but it will be really specific for your app. If you have any questions feel free to reach me out on Twitter: @ankoma22