Ask Your Question
2

How can a mask be added to a UITextFile in Swift?

asked 2021-05-17 11:00:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-01-09 05:00:00 +0000

woof gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-05-17 11:00:00 +0000

Seen: 9 times

Last updated: Jan 09 '23