我想将用户输入格式化为文本字段,因为他(或她)键入。例如,将字母输入"状态"在地址中的字段,我想将输入限制为两个大写字母......
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *afterInput = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSString *letters = [[afterInput componentsSeparatedByCharactersInSet:[[NSCharacterSet letterCharacterSet] invertedSet]] componentsJoinedByString:@""];
textField.text = [[letters substringToIndex:MIN(2, letters.length)] uppercaseString];
return NO;
}
我发现我需要返回NO
,否则我会将原始输入添加到我的格式化更改中。
当用户键入时,这会成功进行格式化,但我还需要告知委托有关文本字段的每个更改。为此,我在init期间添加了(感谢SO)这一行:
[self.textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
问题在于:textFieldDidChange
会在每次更改时被调用,但只有当我回复YES
到shouldChangeCharactersInRange
时才会这样。我需要能够回答NO(因此我可以在打字时格式化)但仍然可以获得更改的消息。
1)我该怎么做? 2)我是否犯了更大的错误,是否有更好的格式化方式,我们可以从文本字段中获取所有正确的消息?谢谢!
答案 0 :(得分:1)
这是一种方法......
而不是为UIControlEventEditingChanged
实现处理程序,处理输入(几乎就像你已经做的那样),然后调用你自己的“文本更改”方法,但是如果文本实际上只调用 改变:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
// get the current text
NSString *origText = textField.text;
// "apply" the user's input
NSString *afterInput = [origText stringByReplacingCharactersInRange:range withString:string];
// filter non-Alpha
NSString *letters = [[afterInput componentsSeparatedByCharactersInSet:[[NSCharacterSet letterCharacterSet] invertedSet]] componentsJoinedByString:@""];
// upper-case the result
NSString *uString = [[letters substringToIndex:MIN(2, letters.length)] uppercaseString];
// if the resulting upper-cased string is NOT the same as what was there to begin with...
if (![origText isEqualToString:uString]) {
// update the text in the text field
textField.text = uString;
// call your own "text changed" method
[self myTextChangedMethod:textField];
}
return NO;
}
- (void)myTextChangedMethod:(UITextField *)tf {
// do what you want here...
NSLog(@"%@", tf.text);
}