Advertisement
neetrath

Untitled

Oct 6th, 2022
1,190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.90 KB | Source Code | 0 0
  1. func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
  2.         if textField == mobileNumberTextField {
  3.             guard let text = textField.text else { return false }
  4.             // All digits entered
  5.             let newString = (text as NSString).replacingCharacters(in: range, with: string)
  6.             if newString.count > 12 {
  7.                 return false
  8.             }
  9.  
  10.             let positionOriginal = textField.beginningOfDocument
  11.             var cursorLocation: UITextPosition?
  12.             if string != "" {
  13.                 // Add
  14.                 if range.location == 3 || range.location == 7 {
  15.                     cursorLocation = textField.position(from: positionOriginal, offset: range.location + NSString(string: string).length + 1)
  16.                 } else {
  17.                     cursorLocation = textField.position(from: positionOriginal, offset: range.location + NSString(string: string).length)
  18.                 }
  19.             } else {
  20.                 // Delete
  21.                 if range.location == 4 || range.location == 8 {
  22.                     cursorLocation = textField.position(from: positionOriginal, offset: range.location + NSString(string: string).length - 1)
  23.                 } else {
  24.                     cursorLocation = textField.position(from: positionOriginal, offset: range.location + NSString(string: string).length)
  25.                 }
  26.             }
  27.             let cleanMobileNumber = newString.replacingOccurrences(of: "-", with: "")
  28.             textField.text = cleanMobileNumber.format(mask: "XXX-XXX-XXXX")
  29.  
  30.             isMobileNumberValid = MobileValidator.isValid(cleanMobileNumber)
  31.  
  32.             if let cursorLoc = cursorLocation {
  33.                 textField.selectedTextRange = textField.textRange(from: cursorLoc, to: cursorLoc)
  34.             }
  35.             return false
  36.         }
  37.         return true
  38.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement