实现UITextField值变化的实时监视

原来认为这个是很简单的基本问题,上网搜索以后发现基本的处理方法大概有四种
1、KVO方式
[textField addObserver:self forKeyPath:@"text" options:0 context:nil];
2、直接添加监视
[textField addTarget:self  action:@selector(valueChanged:)  forControlEvents:UIControlEventAllEditingEvents];
3、注册消息通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldChanged:) name:UITextFieldTextDidChangeNotification object:textField];
4、实现代理方法
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
这个是值变化前调用

但实际测试以后,发现4种方式均不符合textField.text值改变后就实时调用处理函数的目标。
通过界面在textField中编辑输入改变textField.text值的时候,2/4会被触发,1不会触发
但通过代码textField.text = newValue赋值时,1会触发,2/4不触发。

以上都不是特别好用,最后自己在下面的代理中写了一个通知,可以实现值变化后的实时监听
在ViewDidLoad中

[self.bottomView.commentFiled addTarget:self action:@selector(textFieldDidChange:)forControlEvents:UIControlEventEditingChanged]


 -(void)textFieldDidChange:(UITextField *)textField {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeValue" object:textField];
}
在ViewDidLoad中注册这个通知
[[NSNotificationCenter defaultCenter] addObserver:self  selector:@selector(changeValue:)   name:@"changeValue"  object:nil];
实现代理方法
-(void)changeValue:(NSNotification *)notification {
    UITextField *textField = notification.object;

    //要实现的监听方法操作
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值