Mik*_*ong 3 uitextfield ios swift
我正在尝试规范我的应用程序的一些登录/注册要求,因此当用户选择键盘上的"完成"按钮时,我想发送警报,具体取决于他们的输入文本是否有错误.像instagram一样:
我试图阻止在常规字母和数字之外使用任何字符,因此我会用这个问题用一块石头敲掉两只鸟:
1)如何以编程方式访问"完成"按钮到正确的代码,我应该使用什么方法来检测文本字符串中字母和数字之外的任何字符的使用?我知道如何呈现警报视图.
您需要实现textFieldShouldReturn委托方法.在其中,您可以根据您的禁用字符集检查文本字段的文本,并仅在所有字符都有效时关闭键盘.
func textFieldShouldReturn(textField: UITextField) -> Bool {
let forbiddenChars = NSCharacterSet(charactersInString: "@(){}[]")
for c in textField.text.utf16 {
if forbiddenChars.characterIsMember(c) {
println("found forbidden character")
return false
}
}
textField.resignFirstResponder()
return true
}
Run Code Online (Sandbox Code Playgroud)
如果您有多个文本字段,则需要tag在每个文本字段上设置属性,然后在委托方法中对其值进行操作.下面是根据文本字段的标签选择一组不同的无效字符的示例.
func textFieldShouldReturn(textField: UITextField) -> Bool {
let forbiddenChars: NSCharacterSet
if textField.tag == 0 { // e.g. password field
forbiddenChars = NSCharacterSet(charactersInString: "@(){}[]")
} else { // tag != 0, e.g. user name field
forbiddenChars = NSCharacterSet(charactersInString: "*?.<>\\")
}
...
}
Run Code Online (Sandbox Code Playgroud)
在实际应用程序中,您当然应该为标记定义常量,而不是使用文字值.
如果要使用允许字符的白名单而不是黑名单,则只需要翻转条件.
func textFieldShouldReturn(textField: UITextField) -> Bool {
let allowedChars = NSCharacterSet(charactersInString: "abcdefg...")
for c in textField.text.utf16 {
if !allowedChars.characterIsMember(c) {
println("found forbidden character")
return false
}
}
textField.resignFirstResponder()
return true
}
Run Code Online (Sandbox Code Playgroud)
如果要完全拒绝输入无效字符,则需要实现shouldChangeCharactersInRange委托方法并从替换字符串中删除任何不需要的字符.
var myTextField: UITextField
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if count(string) == 0 {
return true
}
let forbiddenChars = NSCharacterSet(charactersInString: "@(){}[]")
var correctedReplacement = ""
for c in string.utf16 {
if !forbiddenChars.characterIsMember(c) {
correctedReplacement += "\(UnicodeScalar(c))"
}
}
if count(correctedReplacement) > 0 {
myTextField.text = (myTextField.text as NSString).stringByReplacingCharactersInRange(range, withString: correctedReplacement)
}
return false
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,UITextField该类没有提供内置方法来为输入的文本设置最大长度.如果要解决此问题,则需要实现shouldChangeCharactersInRange委托方法,并在达到所需的最大长度后立即从替换字符串中删除字符.
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if count(string) == 0 {
return true
}
let maxLength = 10
var trimmedReplacement = ""
for c in string {
if count(textField.text) - range.length + count(trimmedReplacement) >= maxLength {
break
}
trimmedReplacement += "\(c)"
}
if count(trimmedReplacement) > 0 {
myTextField.text = (myTextField.text as NSString).stringByReplacingCharactersInRange(range, withString: trimmedReplacement)
}
return false
}
Run Code Online (Sandbox Code Playgroud)