0

I'm using below algorithm to mask phone number as "(###) ### ## ##". When users start typing in UITextfield, It works great. However, when I delete a space or parentheses then write a number, It add one more number to the textfield and It becomes like "(###) ### ## ###". Where am I doing wrong?

Algorithm:

func applyPatternOnNumbers(pattern: String = "(###) ### ## ##", replacmentCharacter: Character = "#") -> String {
    var pureNumber = self.replacingOccurrences( of: "[^0-9]", with: "", options: .regularExpression)
    for index in 0 ..< pattern.count {
        guard index < pureNumber.count else { return pureNumber }
        let stringIndex = String.Index(encodedOffset: index)
        let patternCharacter = pattern[stringIndex]
        guard patternCharacter != replacmentCharacter else { continue }
        pureNumber.insert(patternCharacter, at: stringIndex)
    }
    return pureNumber
}

How I implement it:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
     if let text = textField.text {
         phoneLbl.text = text.applyPatternOnNumbers()
     }
}

By the way, I'm open to new ways to do it. I checked below posts and AnyFormatterKit framework but nothing helped me.

Formattting Phone number in Swift

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
Emre Önder
  • 2,408
  • 2
  • 23
  • 73
  • Why don't you try this!! https://github.com/appteur/phoneformat – Meera Aug 08 '18 at 12:41
  • Can you provide some examples of input that produce unexpected output? I tried it quickly with `"1234567"` and `"1234567890"` which resulted in `"(123) 456 7"` and `"(123) 456 78 90"` for me. – David Rönnqvist Aug 08 '18 at 12:57
  • After It result "(123)#456 78 90" (# is blank), can you please delete # and type a number? – Emre Önder Aug 08 '18 at 13:36

0 Answers0