您的位置:首页 > 移动开发 > Objective-C

Objective-C实时响应UITextField变化事件

2016-05-19 14:05 393 查看
查看UITextFieldDelegate的API,我们并没有发现像UISearchBarDelegate中textDidChange类似的代理方法。- 而shouldChangeCharactersInRange代理方法里面的textField显示的是变化之前的text,所以做到实时响应UITextField变化事件需要另想办法。

1、注册消息通知:

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeAction:)name:UITextFieldTextDidChangeNotification object:nil];

- (void)changeAction:(NSNotification *)notification{

}

如果需要获取TextField的内容,则需要把textField定义成属性:

NSString *string = _myTextField.text ;

这种方法不会区分是哪个TextField,只要改变就会执行,不适合多个TextField的情况。

2、shouldChangeCharactersInRange:

shouldChangeCharactersInRange方法里的textField虽然显示的是变化之前的text,但是也给出了range和变化的string,替换掉之前的就可以了变化一下就可以了
//textField 字符为@""空字符时候显示提示,并textField显示最小数值
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

//-shouldChangeCharactersInRange gets called before text field actually changes its text, that's why you're getting old text value. To get the text after update use:
NSString * new_text_str = [textField.text stringByReplacingCharactersInRange:range withString:string];//变化后的字符串

return YES;
}


3、给UITextField添加target-action:

[_myTextField addTarget:self action:@selector(textChangeAction:) forControlEvents:UIControlEventEditingChanged];

- (void)textChangeAction:(id)sender {

UITextField textField = (UITextField )sender;

}

这种方法简单好用,推荐使用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: