delegate其實是一種思想!它在開發中經常會使用到。例如最常見的tableView就是使用到了代理。
代理最常用的是反向傳值!!!通知某個屬性發生改變,讓代理去實現!
還有就是解耦!!!
下面簡單介紹一下使用:
使用代理時,首先要明白它是一種思想!!!
記住使用代理就是 6個步驟就可以了!
// 第一步,聲明協議
// 第二步,設置代理屬性
// 第二步,通知代理
// 第4步:遵守協議
// 第五步:設置成為代理
// 第六步:實現代理-
下面直接用一封裝網絡的例子來說明:
首先:創建一個請求類:HTTPReqeust
1.當然是:定制協議和協議方法。
// 1、制定協議
@protocol HTTPRequestDelegate <NSObject>
/**
WithStatus:下載成功與否
request:對象本身(把對象傳過去,因為對象包含了所有信息)
*/
- (void)httpRequestLoadingWithStatus:(BOOL)issucceed request:(HTTPReqeust *)request;
@end
2.設置代理屬性(記得weak)
// 2、代理屬性
@property (nonatomic,weak) id<HTTPRequestDelegate> delegate;
3.在要實現某個功能時,通知上個界面
// 數據下載完成,通知代理
if ([self.delegate respondsToSelector:@selector(httpRequestLoadingWithStatus:request:)]) {
// 3、通知代理
[self.delegate httpRequestLoadingWithStatus:YES request:self];
}
4.上一個頁面ViewController(或另一個頁面,遵守協議,并成為HTTPRequest類的代理)
// 4、遵守協議
@interface ViewController () <HTTPRequestDelegate>
5、設置ViewController成為HTTPRequest的代理
// 調用封裝好的類方法
HTTPReqeust *request = [HTTPReqeust httpReqeustWithStrUrl:@"http://pic14.nipic.com/20110522/7411759_164157418126_2.jpg"];
// 5、設置成為代理
request.delegate = self;// 此時self和self.delegate 都是ViewController
6.實現代理方法,干你想干的事咯!
// 6、實現代理方法
(void)httpRequestLoadingWithStatus:(BOOL)issucceed request:(HTTPReqeust *)request{
if (issucceed) {
// NSLog(@"%@",request.dataDict);
UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
imageView.image = request.dataImage;
[self.view addSubview:imageView];
}
}
1.1 設置控件的狀態
啟用、禁用
@property(nonatomic,getter=isEnabled) BOOL enabled;
選中、不選中
@property(nonatomic,getter=isSelected) BOOL selected;
高亮或者不高亮
@property(nonatomic,getter=isHighlighted) BOOL highlighted;
1.2 設置控件內容的布局
垂直居中方向
@property(nonatomic) UIControlContentVerticalAlignment contentVerticalAlignment;
水平居中方向
@property(nonatomic) UIControlContentHorizontalAlignment contentHorizontalAlignment;
1.3 添加/刪除監聽方法
- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;
- (void)removeTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;
1> UIButton -> UIControl -> UIView
2> UILabel -> UIView
3> UIImageView -> UIView
4> UITextField -> UIControl
* 代理設計模式,在OC中,使用最為廣泛的一種設計模式*
1> 代理的用處是什么?
- 監聽那些不能通過addTarget監聽的事件!
- 主要用來負責在兩個對象之間,發生某些事件時,來傳遞消息或者數據
2> 代理的實現步驟
(1) 成為(子)控件的代理,父親(控制器)成為兒子(文本框)的代理
(2) 遵守協議->利用智能提示,快速編寫代碼
(3) 實現協議方法
一般情況下,能使用代理的地方都可以使用通知!