我创建了一个用户名文本字段,但我希望我的文本字段不接受swift 5中的数字
我尝试过这个芽没起作用
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)
}
答案 0 :(得分:1)
您只需将CharacterSet.decimalDigits
更改为NSCharacterSet.letterCharacterSet()
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if string.rangeOfCharacter(from: .letters) != nil {
return true
} else {
return false
}
}
答案 1 :(得分:0)
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
}
答案 2 :(得分:0)
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
}