Jan 16, 2019:  ~ 2 min read

Improved UIFont naming

In a previous post I was talking about an easier way to create UIFonts:

extension UIFont {

   static func regular(_ size: CGFloat) -> UIFont {
      return .systemFont(ofSize: size, weight: .regular) // Or any other font.
   }
	
   static func medium(_ size: CGFloat) -> UIFont {
      return .systemFont(ofSize: size, weight: .medium)
   }

}

While this indeed improves the usage, it doesn’t address the repeatability of our code. We tend to use one font in several places:

let titleLabel = UILabel(frame: .zero)
titleLabel.font = .medium(16)

// [...] Another part of the app

let otherTitleLabel = UILabel(frame: .zero)
otherTitleLabel.font = .medium(16)

This means that if we’ll ever want to change the size of the title, we’d have to find all the places and do the replacement. Usually, a weight and a size are associated with an element type, like a title, but not always — this will cause even more headaches.

Following DRY practices, we could improve this, by creating a .title font:

extension UIFont {

	@nonobjc static let title = UIFont.medium(16)

}

Now, the call site will look better from a semantic point of view:

let titleLabel = UILabel(frame: .zero)
titleLabel.font = .title

// [...] Another part of the app

let otherTitleLabel = UILabel(frame: .zero)
otherTitleLabel.font = .title

And, in the future, if we’ll want to change the size of the title, we’ll just have to change the static property 👍🏻.

Subscribe to my monthly newsletter.
No spam, unsubscribe at any time.