我试图实时调节UITextfield的输入,这意味着在用户输入时。我有这个字符集,我需要与输入字符串进行比较,并在编辑时如果键入了无根字符,我想传递一个警报。这是我的角色集:
let acceptedChars = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_")
现在我如何实时捕捉特定的文本字段并跟踪其输入?
答案 0 :(得分:3)
试试这个:
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let invalidCharacters = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_").invertedSet
if let range = string.rangeOfCharacterFromSet(invalidCharacters, options: nil, range:Range<String.Index>(start: string.startIndex, end: string.endIndex)) {
return false
}
return true
}
答案 1 :(得分:2)
您可以将textField注册为像
这样的值更改事件textfield.addTarget(self, action:"textFieldDidChange", forControlEvents:UIControlEvents.EditingChanged)
func textFieldDidChange(){
// put your code
}
它适用于您实时输入的每个字符
答案 2 :(得分:1)
var strings: NSString?
类ViewController:UIViewController,UITextFieldDelegate //设置文本字段委托
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{ if(textField .isEqual(your textfield))
{
strings=string;
let acceptedChars = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_").invertedSet;
if (strings!.rangeOfCharacterFromSet(acceptedChars.invertedSet).location != NSNotFound)
{
return true;
}
else
{
return false;
}
}
else
{
return true;
}
}
答案 3 :(得分:0)
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{
if textField.isEqual(<textField whose value to be copied>)
{
<TextField to be updated>.text = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string)
}
return true
}
答案 4 :(得分:0)
一种简单且更高效的委托方法是:
func textFieldDidChangeSelection(_ textField: UITextField) {
print(textField.text)
}