Reputation:
I have a textfield for numbers that is already formatted when user types in the field; it would look like this:
Here is my code:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
phoneNumberTextField.delegate = self
retrieveUserData()
}
func formattedNumber(number: String) -> String {
let cleanPhoneNumber = number.components(separatedBy: CharacterSet.decimalDigits.inverted).joined()
let mask = "(XXX) XXX-XXXX"
var result = ""
var index = cleanPhoneNumber.startIndex
for ch in mask where index < cleanPhoneNumber.endIndex {
if ch == "X" {
result.append(cleanPhoneNumber[index])
index = cleanPhoneNumber.index(after: index)
} else {
result.append(ch)
}
}
return result
}
extension AccounInfotVC: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text else { return false }
let newString = (text as NSString).replacingCharacters(in: range, with: string)
textField.text = formattedNumber(number: newString)
return false
}
}
However, when my view loads; the number is not formatted once its auto populated from the database with this code:
func retrieveUserData(){
db.collection(DatabaseRef.Users).document(userID).getDocument { (snap, error) in
self.phoneNumberTextField?.text = phoneNumber
}
}
so the number gets populated like this:
Any idea how i can get it to populate the textfield in the same format as when user types?
Note that, when I save the phone number, I remove spaces and the characters so number is saved like 1234567889
in the database.
Upvotes: 0
Views: 51
Reputation: 100503
This
self.phoneNumberTextField?.text = phoneNumber
won't trigger shouldChangeCharactersIn
, you need
self.phoneNumberTextField?.text = formattedNumber(number:phoneNumber)
Upvotes: 1