UITextField shouldChangeCharactersInRange doesn

2019-09-10 05:31发布

问题:

I have a UITextField and I am trying to format it as phone number, however I am struggling getting the first letter of the UITextField for some reason.

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{
  if textField == myTextField {
    var updatedTextString : NSString = PartialFormatter().formatPartial(textField.text!)

     self.formattedPhoneNumber(updatedTextString, textField: textField)
  }
 return true
}

func formattedPhoneNumber(updatedTextString: NSString, textField: UITextField) {
     textField.text = updatedTextString as String
     print(updatedTextString)
}

What am I doing wrong?

Please note that I am using PhoneNumberKit in order to format phone number (and use PartialFormatter().formatPartial)


Edit: I tried adding a default + sign in the beginning of textField's text (as the numbers +44..)

var updatedTextString : NSString = PartialFormatter().formatPartial("+\(textField.text!)")

But it went completely wrong. It kept printing ++++ at first and then fixes itself for 4 characters and more.

So it goes like...

   I press 1 - `+1` on UITextField - `+` on console 
 then press 5 - `++15` on UITextField - `++1` on console 
 then press 6 - `+++156` on UITextField - `+++15` on console

 then press 8 - `+1568` on UITextField - `+1 56` on console 
  // so it magically fixed itself after 4 chars.

 Also removing everything leaves `+++` on UITextField and `++++` on console
 and doesn't delete more

What am I doing wrong?


Edit 2:

I tried using the answer posted below. However now, it's just plain numbers. They are not grouped with PartialFormatter().formatPartial()

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{
  if textField == myTextField {
    let textString : NSString = textField.text!
    let candidateString : NSString = textString.stringByReplacingCharactersInRange(range, withString: string)    
    let updatedTextString : NSString = PartialFormatter().formatPartial(candidateString as String)

    self.formattedPhoneNumber(updatedTextString, textField: textField)
  }
  return true
}

回答1:

The shouldChangeCharactersInRange() function is asking whether the change should be applied but it has not yet allowed your textfield to be modified.

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{
  if textField == myTextField {
    let textString : NSString = textField.text!
    let candidateString : NSString = textString.stringByReplacingCharactersInRange(range, withString: string)    
    let updatedTextString : NSString = PartialFormatter().formatPartial(candidateString as String)
    print(updatedTextString)
    textField.text = updatedTextString
  }
  return true
}