Ios 键入UITextField时,获取其内部的整个文本的简单方法是什么?
当用户输入UITextField时,我需要实时了解文本字段中的整个字符串。我做这件事的方法是听电话。这个回调的问题是,它是在实际插入额外文本之前触发的。由于这一点以及其他各种各样的情况,我需要编写这段极其复杂的代码。有没有一种更简单(代码更少)的方法来做同样的事情Ios 键入UITextField时,获取其内部的整个文本的简单方法是什么?,ios,objective-c,cocoa-touch,uitextfield,Ios,Objective C,Cocoa Touch,Uitextfield,当用户输入UITextField时,我需要实时了解文本字段中的整个字符串。我做这件事的方法是听电话。这个回调的问题是,它是在实际插入额外文本之前触发的。由于这一点以及其他各种各样的情况,我需要编写这段极其复杂的代码。有没有一种更简单(代码更少)的方法来做同样的事情 - (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString* entireString = nil;
if (string.length == 0) {
// When hitting backspace, 'string' will be the empty string.
entireString = [textField.text substringWithRange:NSMakeRange(0, textField.text.length - 1)];
} else if (string.length > 1) {
// Autocompleting a single word and then hitting enter. For example,
// type in "test" and it will suggest "Test". Hit enter and 'string'
// will be "Test".
entireString = string;
} else {
// Regular typing of an additional character
entireString = [textField.text stringByAppendingString:string];
}
NSLog(@"Entire String = '%@'", entireString);
return YES;
}
我甚至不愿意和代表打交道。只需使用
UITextFieldTextDidChangeNotification
即可在事后获得更改通知。然后,您不必担心将更改附加到字符串,您只需访问整个文本即可
[[NSNotificationCenter defaultCenter] addObserverForName:UITextFieldTextDidChangeNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
NSString *string = someTextFieldReference.text;
}];
或者,正如post@warpedspeed链接中的答案所指出的,您可以为文本字段的编辑更改控件事件添加一个目标,如下所示:
[myTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
- (void)textFieldDidChange:(UITextField *)sender
{
NSLog(@"%@",sender.text);
}
你看到这个了吗?