使用协议代理的步骤
先创建协议
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];
}
}
本文介绍如何使用代理模式来解耦iOS应用中的UIButton和UIImageView组件,通过定义协议、实现代理方法及设置代理对象等步骤,使得视图组件能响应用户点击事件并改变背景颜色。
1633

被折叠的 条评论
为什么被折叠?



