Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

A mask can be added to a UITextField in Swift by using the UITextFieldDelegate protocol method textField(_:shouldChangeCharactersIn:replacementString:).

Here is an example implementation to add a phone number mask to a UITextField:

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var phoneNumberTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        phoneNumberTextField.delegate = self
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if textField == phoneNumberTextField {
            // create a character set of allowed phone number characters
            let allowedCharacterSet = CharacterSet(charactersIn: "0123456789-() ").inverted

            // remove any characters not in the allowed set and format the phone number
            let filteredString = string.components(separatedBy: allowedCharacterSet).joined(separator: "")
            let formattedString = formatPhoneNumber(text: textField.text ?? "", replacementString: filteredString)

            // set the formatted phone number as the text in the textField
            textField.text = formattedString

            return false
        }
        return true
    }

    // function to format a phone number as (###) ###-####
    func formatPhoneNumber(text: String, replacementString string: String) -> String {
        let count = text.count + string.count
        if count > 10 {
            return text
        }

        let removingLastChar = (count < text.count)

        var index = text.startIndex
        var formattedString = ""

        for char in text {
            if formattedString.count == 0 {
                formattedString = "(\(char)"
            } else if formattedString.count == 4 {
                formattedString += ") \(char)"
            } else if formattedString.count == 9 {
                formattedString += "-\(char)"
            } else {
                formattedString += "\(char)"
            }
            index = text.index(after: index)
        }

        if !removingLastChar && count == 3 {
            formattedString += ") "
        } else if !removingLastChar && count == 6 {
            formattedString += "-"

        }
        return formattedString
    }
}

In this example, the formatPhoneNumber function formats the phone number input as "###-###-####". The UITextFieldDelegate method textField(_:shouldChangeCharactersIn:replacementString:) is called every time the user enters or deletes a character in the phone number text field. The method filters out any characters not in the allowed set, formats the phone number using the formatPhoneNumber function, and updates the text field with the formatted phone number.