知道textField中的完整更改字符串:shouldChangeCharactersInRange:replacementString:

Ben*_*der 32 cocoa-touch objective-c uitextfield

我刚刚问了一个关于如何监控a的变化UITextField并收到此响应的问题:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)replacementStr {
    // Enable "Next" if you like what's entered in the replacementStr
}
Run Code Online (Sandbox Code Playgroud)

这可行,但替换字符串不是整个字符串,只是它添加的内容.我怎样才能获得整个字符串?我的目标是查看文本字段中的字符串是空白还是等于某个数字(在不同的场景中).

请注意,在这种情况下,文本字段的出口不起作用,因为在字段中的文本更改之前调用此方法.

Jos*_*ell 78

NSString * proposedNewString = [[textField text] stringByReplacingCharactersInRange:range withString:replacementString];
Run Code Online (Sandbox Code Playgroud)


Irf*_*fan 13

Swift版本

Swift中我们需要将textField's文本转换为NSString.以下内容非常有用:

let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
Run Code Online (Sandbox Code Playgroud)