Font Management in Swift

Tram Ho

Preamble:

In application development, fonts play an important role in interface design. Selecting fonts suitable for UI interface will help our application more eye-catching and more convenient to use.

Problem:

In case your project is assigned to customers for final inspection before being submitted to the Appstore. In the end, your app is ok by the customer, but just make small adjustments to the font or font size to enlarge to 1 size and you are assigned to edit the font. As usual you will have to find each UILabel or UITextField on each StoryBoard in the project. It will be very easy if the number of screens is small but imagine there are dozens of screens, it is difficult to find each label. To solve this task quickly we need a measure to manage the change of font or font size.

Method:

  • Step 1:
    • Bring the fonts you need into the project. Drag and drop fonts into the project resource.

  • Step 2:
    • Register your fonts in the Info.plist file under the Fonts provided by application (UIAppFonts) key.

  • Step 3:
    • Make sure the fonts you add to the project, check the font has been registered or not with the Utility.logAllAvailableFonts () function. (All fonts included in the project will be printed in the debug console).

Using:

  • Usually we register the font as well as the font size by initializing after UIFont (name: size 🙂 We need to avoid such hard code to easily change the font or font size. We will use 2 enums to do this, one to manage fonts, the other to manage font size.

  • Enum FontName is used to handle all the fonts that we have added to the project. Enum StandardSize is used to handle font sizes in projects.
  • In some cases we will need to use the system font or font sizes larger or smaller so we will add 2 Enum to handle that.

  • With the FontType enum, it is easy to use the default font or the font added from the outside. Similarly, Enum FontSize helps you choose the pre-installed typefaces in Enum StandardSize or use custom fonts.
  • We will now encapsulate the enum above in the struct Font. This makes it easy to create the font and font size easily.

  • We have not yet added any mechanism to initialize UIFont. That will be done via the extension below.

Use:

  1. initialize UIFont in the usual way:

  1. And here is how to initialize with the syntax according to the architecture we have implemented above, will look more intuitive and will help us easier to maintainance.

Share the news now

Source : Viblo