简体   繁体   中英

Adding Prefixed Character to UITextField

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)
}

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM