我有一个文本字段,可用作密码输入。我创建了4个数组
upperCaseAll = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
lowerCaseAll = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
numberAll = [1 ,2, 3, 4, 5, 6, 7, 8, 9, 0]
specialCharAll = ["-", "/", ":", ";", "(", ")", "$", "&", "@", "\"", ".", ",", "?", "!", "'", "[", "]", "{", "}", "#", "%", "^", "\\", "|", "~", "<", ">", "€", "£", "¥", "•", ".", ","]
我试图让用户输入每种类型的角色中的至少一种。 我有4个文本视图,一旦满足每个规则,将从红色变为绿色。 然后,当满足所有规则时,红色文本视图变为绿色并启用登录按钮
我的问题是我如何检查文本字段以查看它是否满足规则?我想它必须超时检查每个数组输入一个字符
哦,数字也应该是Ints还是字符串?
由于
答案 0 :(得分:2)
如果您使用Set
而不是Array
,则会更容易。这是一个例子:
private let upperCaseAll = Set("ABCDEFGHIJKLMNOPQRSTUVWXYZ".characters)
private let lowerCaseAll = Set("abcdefghijklmnopqrstuvwxyz".characters)
private let numberAll = Set("0123456789".characters)
private let specialCharAll = Set("-/:;()$&@\".,?!'[]{}#%^\\|~<>€£¥".characters)
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// Determines what the new value of the text field will be
let newText = range.length == 0 ? textField.text! + string : (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)
// Turn that string into a Set of Characters
let characters = Set(newText.characters)
let hasUpperCase = !characters.intersect(self.upperCaseAll).isEmpty
let hasLowerCase = !characters.intersect(self.lowerCaseAll).isEmpty
let hasNumber = !characters.intersect(self.numberAll).isEmpty
let hasSpecialChar = !characters.intersect(self.specialCharAll).isEmpty
// Now turn your 4 other views to green/red as needed
print("hasUpperCase = \(hasUpperCase), hasLowercase = \(hasLowerCase), hasNumber = \(hasNumber), hasSpecialChar = \(hasSpecialChar)")
...
return true
}
答案 1 :(得分:1)
您可以使用UITextFieldDelegate
来完成请参阅Apple Docs - textField(_:shouldChangeCharactersInRange:replacementString:)
只要用户操作导致其文本,文本字段就会调用此方法 改变。使用此方法验证文本的类型 用户。例如,您可以使用此方法来阻止用户 输入除数值之外的任何内容。
但是你应该考虑使用正则表达式来检查密码字符串。那会更方便。