标签:
委托是指给一个对象提供机会对另一对象中的变化做出反应或者相应另一个对象的行为。其基本思想是协同解决问题。
以上情况,结果都一样:对象B是对象A的代理(delegate)
1.委托(A)需要做的工作有:
3.设置代理(delegate)对象 (比如myView.delegate = xxxx;)
4.在恰当的时刻调用代理对象(delegate)的代理方法,通知代理发生了什么事情
2.代理(B)需要做的工作有:
实例:界面View底部点击"加载更多数据",通知控制器请求数据,并刷新表格。
定义代理协议、定义代理方法
#import <UIKit/UIKit.h> @class TuangouFooterView; // 定义一个协议,控件类名 + Delegate @protocol TuangouFooterViewDelegate <NSObject> // 代理方法一般都定义为@optional @optional // 代理方法名都以控件名开头,代理方法至少有1个参数,将控件本身传递出去 -(void)tuangouFooterDidClickedLoadBtn:(TuangouFooterView *)tuangouFooterView; @end @interface TuangouFooterView : UIView // 定义代理。要使用weak,避免循环引用 @property(nonatomic,weak) id<TuangouFooterViewDelegate> delegate; @end
在恰当的时刻调用代理对象(delegate)的代理方法,通知代理
// 通知代理,先判断是否有实现代理的方法。
if ([self.delegate respondsToSelector:@selector(tuangouFooterDidClickedLoadBtn:)]) {
[self.delegate tuangouFooterDidClickedLoadBtn:self];
}
实现代理
@interface ViewController ()<TuangouFooterViewDelegate>
设置代理
TuangouFooterView *footerView=[TuangouFooterView footerView];
footerView.delegate=self;// 设置当前footerView为代理
实现代理方法
/**
* 加载更多的数据
*/
- (void)tuangouFooterDidClickedLoadBtn:(TuangouFooterView *)tuangouFooterView
{
#warning 正常开发:发送网络请求给远程的服务器
// 1.添加更多的模型数据
Tuangou *tg = [[Tuangou alloc] init];
tg.icon = @"ad_01";
tg.title = @"新增加的团购数据..";
tg.price = @"100";
tg.buyCount = @"0";
[self.tgs addObject:tg];
// 2.刷新表格(告诉tableView重新加载模型数据, 调用tableView的reloadData)
[self.tableView reloadData];
}
标签:
原文地址:http://www.cnblogs.com/xvewuzhijing/p/4904638.html