How to Add a TextField with a Mask for Phone Numbers in SwiftUI

Written by anastasiatiurina | Published 2023/01/24
Tech Story Tags: swift | ios | ios-app-development | ios-development | ios-apps | iosdevelopment | programming | swiftui

TLDRSwiftUI doesn’t have phone mask tools. Therefore, you’ll need to use UIKit. In this article, we will look at: using a phone mask when registering written in UIKit to a SwiftUI project. You can see all the code on the public** GitHub repository.via the TL;DR App

SwiftUI doesn’t have phone mask tools. Therefore, you’ll need to use UIKit.

In this article, we will look at: using a phone mask when registering written in UIKit to a SwiftUI project.

You can see all the code on the public GitHub repository

How to Implement a Phone Number Mask in SwiftUI

1. Create a View on SwiftUI

2. Create a TextFieldContainer structure that will correspond to UIViewRepresentable, contain the necessary methods, and the container class

Here, I’ll explain more about the terms above:

P.S it is important to be able to read and understand the documentation, so I refer to it.

What is UIViewRepresentable?

This question is well answered by the Apple documentation:

“A wrapper for a UIKit view that you use to integrate that view into your SwiftUI view hierarchy.

This means that with UIViewRepresentable we can inject UIKit elements into our SwiftUI project whenever we need to.

In other words, this is a layer that is friends with two different frameworks (UIKit and SwiftUI)

There is also UIHostongController which is used in reverse when we want to use a SwiftUI element in a UIKit module.

What is a Coordinator?

And here again, Apple documentation comes to the rescue:

“When you want your view to coordinate with other SwiftUI views, you must provide a Coordinator instance to facilitate those interactions.”

You can do without it, but if we want to create a relationship between elements, then the coordinator will help establish this dependency.

UIViewRepresentable has several methods:

Everything is extremely simple here, I will not give additional comments, since without makeUIView it will not be possible to draw our TextField with a mask in SwiftUI, and without updateUIView, it will not be possible to change it

3. Create a class with a method that will format the entered phone number.

The class must match ObservableObject so that we can use the function in our view on SwifUI

4. Add to our view Structure from TextField to UIKIt and a class to call the method

5. It decorates the view beautifully

Look at the result!

Hope this article helps you in your projects. Good luck and see you soon!


Written by anastasiatiurina | iOS developer
Published by HackerNoon on 2023/01/24