Simple PhoneFormatter for UITextField

Greetings to all! Quite often you can find a form for entering a phone number in mobile applications. And the most common use cases are user registration and authorization. However, Apple does not offer a native solution for formatting a phone number. This post will demonstrate the development process of a fairly simple and at the same time high perfrormance PhoneFormatter.

PhoneFormatter development

By searching on this topic

and analysing the existing solutions, there are the common basis on which a PhoneFormatter is based. This is the mask, or, as it is more commonly called, pattern, according to which the text is formatted.

The most common ways of specifying a mask is to denote any digit with the # symbol and any letter with the * symbol. Although sometimes numbers are denoted by the $ symbol, this is still a less common approach, so the first option is better.

Further it is necessary to create method that can be used to convert a plain string with a phone number, for example 12345678910, to the formatted string +1 (234) 567–89–10.

When implementing the algorithm, it should be taken into account that the plain string can also include characters other than numbers, therefore, before starting formatting, it is necessary to "clear" the plain string. It is most appropriate to use CharacterSet to solve this problem, since the required character set is already contains only necessary symbols and this object implements the SetAlgebra protocol, which allows you to filter characters with maximum performance.

let allowedCharachters = CharacterSet.alphanumericslet filteredInput = String(plainString.unicodeScalars.filter(allowedCharachters.contains))

The formatting algorithm is actually simple, although the description may seem complicated at first.

The loop iterates over the characters of the plain string and mask. Each character in the plain string is checked against the current character in the mask. For example, if the current character of the mask is # (number), then if the current character of the plain string is a number, then the character is saved to the formatted string and then the next character of the mask, and the next character of the plain string will be checked. Otherwise, the current mask character and the next character of the plain string are checked. If the current mask character is not a digit or a letter (for example, the bracket "(, [, {"), then this character is saved into a formatted string, and then the next mask character and the current character of an plain string will be checked).

Surely the explanation could be misleading, but in conjunction with the code given above, for sure, everything will become much more clear.

Using PhoneFormatter in UITextField

It is worth mentioning right away that Formatter can be anything, not only for formatting a phone number. For example, to format a bank card number, e-mail address, etc. Therefore, it is worth at least to create the foundation for the future use of a different kinds of formatter. For this purpose, the protocol is perfect, with the necessary interface:

The first method was discussed above, and the second is intended to be called from the textField (_:shouldChangeCharactersIn:replacementString) method of UITextFieldDelegate, since this is the only way to perform formatting immediately (character by character) as user type.

The algorithm should also be straightforward. First, the string entered by the user is determined, and then it is processed by the formatter. After that, the already formatted string is displayed to the user. However, pay attention to the line

return formatted.isEmpty

The fact is that when using the system autofill (when the keyboard prompts for a phone number), UITextField is filled with a space (maybe some prefix in foreign countries), and only after that, with the suggested phone number. Therefore, when replacing with

return false

system autofill won’t fill the UITextField, which is of course unacceptable.

In this way, in order for the formatting to work immediately, as the phone number is entered, it remains to implement the UITextFieldDelegate delegate

The result is expectedly amazing:

Bonus: SnappyTextField

Recently, UITextField with moving up and changing their size placeholders has become popular.

It’s also a pretty simple thing to implement.

Should use UILabel as a placeholder, since the easiest way to implement such an animation is using CGAffineTransofrm. Is is enough to add the UILabel to the UITextField and make the necessary transformations on this label. At the same time, this label displays the placeholder text, so it is needed to change the implementation of the placeholder and attributedPlaceholder properties.

If you look closely, the animation is performed at the moment when the text appears, or is completely removed from the input field. Therefore, once again, use the UITextFieldDelegate's method textField (_:shouldChangeCharactersIn:replacementString). It is worth remembering that the delegate can also be set outside the class (for example, if need to format the phone number). For this reason save the delegate specified from the outside of the class separately.


The publication describes the simplest and at the same time high performance implementation of PhoneFormatter, the capabilities of which can be expanded in accordance with the needs. Let me wish you a good day. That’s it.




Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How Pygame works in five minutes

Window to the World: Skybox

PHP Became Strongly-Typed

AWS 101 — Guide For Dummy(EC2)

Async-Lock Mechanism on Asynchronous Programing

Calculator-Python with GUI

Display hierarchical data as list with search feature

The 6 New Ways I Look At Java

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ace Rodstin

Ace Rodstin

More from Medium

How to resolve the swiping right action when trying to navigate to a previous screen in iOS.

Swift Essentials | Enums

Every iOS developer should know these Xcode tricks

Swift 5.6: Property Wrappers