對UITextField內容實時監聽長度和內容
阿新 • • 發佈:2019-02-15
在UISearchBar中,當輸入資訊改變時,它就會呼叫textDidChange函式,但是UITextField沒有這個功能,唯一與這個類似的
shouldChangeCharactersInRange函式,也是在檔案還沒有改變前就呼叫了,而不是在改變後呼叫,要想實現這個功能,我們可以增加事件監聽的方式,這個與java的listener類似.先來看看objective-c提供的介面:
// add target/action for particular event. you can call this multiple times and you can specify multiple target/actions for a particular event.
// passing in nil as the target goes up the responder chain. The action may optionally include the sender and the event in that order
// the action cannot be NULL.
- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;
怎麼去使用這個介面呢?主要分為兩步,第一步就是在UItextField元件中增加對檔案編輯改變時事件的監聽,然後再實現監聽器監聽到事件時,所呼叫的方法.
//第一步,對元件增加監聽器
[textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
...
//第二步,實現回撥函式
- (void) textFieldDidChange:(id) sender {
UITextField *_field = (UITextField *)sender;
NSLog(@"%@,%d",[_field text],_field.text.length);
}
shouldChangeCharactersInRange函式,也是在檔案還沒有改變前就呼叫了,而不是在改變後呼叫,要想實現這個功能,我們可以增加事件監聽的方式,這個與java的listener類似.先來看看objective-c提供的介面:
// add target/action for particular event. you can call this multiple times and you can specify multiple target/actions for a particular event.
// passing in nil as the target goes up the responder chain. The action may optionally include the sender and the event in that order
// the action cannot be NULL.
- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;
怎麼去使用這個介面呢?主要分為兩步,第一步就是在UItextField元件中增加對檔案編輯改變時事件的監聽,然後再實現監聽器監聽到事件時,所呼叫的方法.
//第一步,對元件增加監聽器
[textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
...
//第二步,實現回撥函式
- (void) textFieldDidChange:(id) sender {
UITextField *_field = (UITextField *)sender;
NSLog(@"%@,%d",[_field text],_field.text.length);
}