我正在该屏幕上创建一个OTP屏幕,我添加了6个文本字段。现在我想限制只输入一个字符&也想限制用户不要输入任何特殊的字符。下面是我使用的代码,请查看代码&让我知道出了什么问题?
let notAllowedCharacters = "!@#$%^&*()_+{},./[]?:;";
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange,replacementString string: String) -> Bool
{
guard let text = textField.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
if newLength <= 1 {
return true
}
else {
let set = NSCharacterSet(charactersIn: notAllowedCharacters);
let filtered = string.components(separatedBy: set as CharacterSet).joined(separator: "")
return filtered == string;
}
}
答案 0 :(得分:0)
在检查字符长度时,您需要添加NSCharacterSet
的控件。否则,如果总有一个字符,则无论字符如何都将始终为真。将您的代码更新为以下内容,它将适用于您:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange,replacementString string: String) -> Bool {
guard let text = textField.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
let set = NSCharacterSet(charactersIn: notAllowedCharacters)
if newLength <= 1 && !(string.rangeOfCharacter(from: set as CharacterSet) != nil) {
return true
} else {
return false
}
}