代替代理
1.自定义一个View控件,并添加一个按钮
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor blueColor];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(10, 10, 50, 50);
btn.backgroundColor = [UIColor redColor];
[self addSubview:btn];
[btn addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
}
return self;
}
- (void)clickButton:(UIButton *)btn {
}
2.如果使用代理,需要创建一个delegate属性,在clickButton:中执行[self.delegate xxx],并在vc中实现代理方法。
3.但通过RAC就方便许多,直接在VC中添加自定义view
@property (nonatomic, strong) MyView *v;
4.要接收点击事件直接执行
[[_v rac_signalForSelector:@selector(clickButton:)] subscribeNext:^(RACTuple * _Nullable x) {
NSLog(@"%@", x);
}];
5.运行结果如图:

运行结果
代替KVO
1.代替KVO有两种方式
[_v rac_observeKeyPath:@"frame" options:NSKeyValueObservingOptionNew observer:nil block:^(id value, NSDictionary *change, BOOL causedByDealloc, BOOL affectedOnlyLastComponent) {
NSLog(@"%@", value);
}];
[[_v rac_valuesForKeyPath:@"frame" observer:nil] subscribeNext:^(id _Nullable x) {
NSLog(@"%@", x);
}];
监听事件
- 监听按钮点击事件
[[_btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
NSLog(@"%@", x);
}];
- 监听文本框输入
[[_tf rac_textSignal] subscribeNext:^(NSString * _Nullable x) {
NSLog(@"%@", x);
}];
代替通知
如监听键盘出现
[[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIKeyboardWillShowNotification object:nil] subscribeNext:^(NSNotification * _Nullable x) {
NSLog(@"%@", x);
}];