2020-09-28

protocol创建一系列方法的列表,其中声明的方法可以被任何类实现。这种模式一般称为代理模式

只要想监听一个类

1.声明代理

声明一个代理

@protocol ButtonDelegate <NSObject>
-(void) onClick;
@end

2.被监听者,比如一个按钮被点击。在属性中实现了监听器,这时候就可以出发协议中的函数

@interface button : NSObject

-(void)click;

@end
@implementation button
-(void)click{
NSLog(@"我被点击了");
[_delegate onClick];
}
@end

3.监听者,要设置代理

@interface buttonListener : NSObject<ButtonDelegate>
@end

 

@implementation

//实现代理的函数
-(void)onClick{
NSLog(@"按钮被点击了");
}

@end

 

main 

button *btn = [[button alloc]init];

buttonlistener * = [[buttonlistener  alloc]init];

btn.delegate = buttonlistener;

;

///

多个按钮被点击了咋办

1.声明代理

@protocol ButtonDelegate <NSObject>
-(void) onClick:(button*)btn;
@end

2.被监听的button

if([_delegate respondsToSelector:@selector(onClick:)])
{

[_delegate onClick:self];

}else
{

NSLog(@"监听者未实现");

}

 

本文地址:https://blog.csdn.net/yonggandess/article/details/108850392

(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐