常用的监听方式有三种:
第一种:使用的是UITextField的代理方法监听,代码如下:
self.textField.delegate = self;
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *inputString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSLog(@"inputString: %@", inputString);
return YES;
}
第二种:使用通知的方式实现监听,代码如下:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didTextFieldChanged:) name:UITextFieldTextDidChangeNotification object:nil];
- (void)didTextFieldChanged:(NSNotification *)notification
{
UITextField *textField = notification.object;
NSString *inputString = textField.text;
NSLog(@"inputString: %@", inputString);
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
第三种:使用事件监听,也是最简单的方法
[self.textField addTarget:self action:@selector(textFieldChanged:) forControlEvents:UIControlEventEditingChanged];
- (void)textFieldChanged:(UITextView *)textField
{
NSString *text = textField.text;
NSLog(@"inputString: %@", text);
}