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