Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
- if textField == mobileNumberTextField {
- guard let text = textField.text else { return false }
- // All digits entered
- let newString = (text as NSString).replacingCharacters(in: range, with: string)
- if newString.count > 12 {
- return false
- }
- let positionOriginal = textField.beginningOfDocument
- var cursorLocation: UITextPosition?
- if string != "" {
- // Add
- if range.location == 3 || range.location == 7 {
- cursorLocation = textField.position(from: positionOriginal, offset: range.location + NSString(string: string).length + 1)
- } else {
- cursorLocation = textField.position(from: positionOriginal, offset: range.location + NSString(string: string).length)
- }
- } else {
- // Delete
- if range.location == 4 || range.location == 8 {
- cursorLocation = textField.position(from: positionOriginal, offset: range.location + NSString(string: string).length - 1)
- } else {
- cursorLocation = textField.position(from: positionOriginal, offset: range.location + NSString(string: string).length)
- }
- }
- let cleanMobileNumber = newString.replacingOccurrences(of: "-", with: "")
- textField.text = cleanMobileNumber.format(mask: "XXX-XXX-XXXX")
- isMobileNumberValid = MobileValidator.isValid(cleanMobileNumber)
- if let cursorLoc = cursorLocation {
- textField.selectedTextRange = textField.textRange(from: cursorLoc, to: cursorLoc)
- }
- return false
- }
- return true
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement