1

I have a UITextField for formatting phone numbers. I am trying to add a "+" sign prefix as the first character, that can't be removed. Formatting & checks are working fine, but having a prefix doesn't seem to work..

In the beginning, it doesn't present the "+" sign however, if I write a character and delete, it will present the "+" sign. I know this is because the shouldChangeCharactersInRange would not get called before I type the first number, however why doesn't the makePrefix() function add the prefix?

So I am stuck at the time where 'the user clicked on the UITextField but hasn't entered a character yet'..

override func viewDidLoad() {
        super.viewDidLoad()

        makePrefix()
}

func makePrefix() {
    let attributedString = NSMutableAttributedString(string: "+")
    attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.whiteColor(), range: NSMakeRange(0,1))
    phoneTextField.attributedText = attributedString
}

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{
    if textField == phoneTextField {

        textField.typingAttributes = [NSForegroundColorAttributeName:UIColor.whiteColor()]

        return false
    }

    return true

}

func formattedPhoneNumber(updatedTextString: NSString, textField: UITextField) {
        textField.text = "\(updatedTextString as String)"
        print(updatedTextString)
}
senty
  • 12,385
  • 28
  • 130
  • 260

2 Answers2

2

Check textFieldDidBeginEditing, it will get called when the textField becomes first responder.

Check if the text is begin with "+", if not call your makePrefix().

dichen
  • 1,643
  • 14
  • 19
1

Elegant solution using leftView to UITextField

let prefix = UILabel()
prefix.text = "+"
// set font, color etc.
prefix.sizeToFit()

phoneTextField.leftView = prefix
phoneTextField.leftViewMode = .always // or .whileEditing
Prakash
  • 812
  • 6
  • 16