代理delegate
1>代理的用处是什么?
监听那些不能通过addTarget监听的事件
主要用开负责在两个对象之间,发生某些事件时,传递或发送消息
当我们需要 监听某些事件时,但苹果没有提供相关监听方法(addtage),那我们就让别那个控件挂上代理,相应的代码遵守协议,这样架起来,产生监听
添加delegate方法:
(1)成为(子)控件的代理,父亲(控制器)成为儿子(文本框)的代理;
(2)遵守协议-》利用智能提示,快速编写代码
(3)实现协议方法
UITextFielddelegate代理事件方法:
1 @protocol UITextFieldDelegate <NSObject> 2 3 @optional 4 5 - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField; // return NO to disallow editing. 6 - (void)textFieldDidBeginEditing:(UITextField *)textField; // became first responder 7 - (BOOL)textFieldShouldEndEditing:(UITextField *)textField; // return YES to allow editing to stop and to resign first responder status. NO to disallow the editing session to end 8 - (void)textFieldDidEndEditing:(UITextField *)textField; // may be called if forced even if shouldEndEditing returns NO (e.g. view removed from window) or endEditing:YES called 9 10 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string; // return NO to not change text 11 12 - (BOOL)textFieldShouldClear:(UITextField *)textField; // called when clear button pressed. return NO to ignore (no notifications) 13 - (BOOL)textFieldShouldReturn:(UITextField *)textField; // called when 'return' key pressed. return NO to ignore. 14 15 @end
限制字符长度:
此次笔记只是记录原生控件的代理方法,后续还会有自己编写的控件的代理模式。