Reputation: 37
i created a username textfield and i want my textfield do not accept the numbers in swift 5
i tried this bud didnt work
func OnlyCharacter(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let allowedcharacters = CharacterSet.decimalDigits
let characterset = CharacterSet(charactersIn: string)
return allowedcharacters.isSuperset(of: characterset)
}
Upvotes: 0
Views: 125
Reputation: 4917
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let characterSet = CharacterSet.letters //accept letters only here
if string.rangeOfCharacter(from:characterSet.inverted) != nil {
return false
}
return true
}
Upvotes: 0
Reputation: 2336
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let non_digits = NSCharacterSet.letters.inverted
let range = string.rangeOfCharacter(from: non_digits)
if range != nil { // found an invalid
return false
}
return true
}
Upvotes: 0
Reputation: 3494
You have to change only CharacterSet.decimalDigits
to NSCharacterSet.letterCharacterSet()
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if string.rangeOfCharacter(from: .letters) != nil {
return true
} else {
return false
}
}
Upvotes: 1