Reputation: 467
I am using phone number texfield, now i am using this format for texfield (#) ### ### ###, now issue is that i want first character 0 as compulsary, like this (0) 959 554 545, so user enter whatever first character must be typed 0,
this is my code
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let newString = textField.text
if ((newString == "") && (newString?.count == 0)){
txtMobileNumber.text = "0"
return true
}else if ((newString?.count)! > 0){
return true
}
return false
}
Upvotes: 0
Views: 758
Reputation: 15748
In shouldChangeCharactersIn
method return false if new string count is greater than 15. Else remove (0)
and empty spaces, then if the string isn't empty add (0)
at the beginning. Then split the string by every 3 characters and join all string with space separator.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
var oldText = (textField.text! as NSString).replacingCharacters(in: range, with: string)
if oldText.count > 15 { return false }
oldText = oldText.replacingOccurrences(of: "(0)", with: "").replacingOccurrences(of: " ", with: "")
if !oldText.isEmpty {
oldText = "(0)" + oldText
}
let newText = String(stride(from: 0, to: oldText.count, by: 3).map {
let sIndex = String.Index(encodedOffset: $0)
let eIndex = oldText.index(sIndex, offsetBy: 3, limitedBy: oldText.endIndex) ?? oldText.endIndex
return String(oldText[sIndex..<eIndex])
}.joined(separator: " "))
textField.text = newText
return false
}
Upvotes: 3
Reputation: 21
If you create Enum, you can choice your textField type and make the extension properties for this field
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
if cellType == .phone {
guard var sanitizedText = textField.text else { return true }
if !sanitizedText.isEmpty && !sanitizedText.hasPrefix("(0)") {
sanitizedText.text = "(0)" + sanitizedText
}
}
}
Upvotes: 1
Reputation: 24341
In shouldChangeCharactersIn
method of UITextFieldDelegate
,
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if let text = textField.text {
let str = (text as NSString).replacingCharacters(in: range, with: string).replacingOccurrences(of: "(0)", with: "")
if !str.isEmpty {
textField.text = "(0)" + str
} else {
textField.text = nil
}
}
return false
}
Append (0)
to the newly created string
, everytime the textField
is edited.
Upvotes: 2