使用協議代理的步驟
先創建協議
1.遵守協議
2.實現協議中的方法
3.設置代理(添加代理對象爲實例變量) –(誰需要代理 在那個類裏聲明實例變量)
4.添加設置代理對象的方法(set方法)
5.讓代理幹活(讓代理去調用協議中的方法)
6.從main創建對象 設置代理對象
點擊UIImageView換背景色
創建協議
@protocol UIButtonImageViewDelegate <NSObject>
// 捕獲點擊事件
- (void)buttonImageViewClick:(ButtonImageView *)view;
@end
實現代理方法
- (void)buttonImageViewClick:(ButtonImageView *)view{
//buttonImageView.backgroundColor = [UIColor cyanColor];
NSLog(@"dd");
// 不管是target/action還是代理設計模式 還是MVC設計模式 中心只有一個:解耦(降低類和類之間的耦合性)
view.backgroundColor = [UIColor cyanColor];
}
設置代理
@property (nonatomic, assign) id <UIButtonImageViewDelegate> delegate;
代理調用協議中的方法
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
// 讓代理幹活
// 讓代理去調用協議方法
// 保護:判斷下代理有沒有實現這個方法
if ([_delegate respondsToSelector:@selector(buttonImageViewClick:)]) {
[_delegate buttonImageViewClick:self];
}
}