代替代理
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.如果使用代理,需要創(chuàng)建一個delegate屬性,在clickButton:中執(zhí)行[self.delegate xxx],并在vc中實現(xiàn)代理方法。
3.但通過RAC就方便許多,直接在VC中添加自定義view
@property (nonatomic, strong) MyView *v;
4.要接收點擊事件直接執(zhí)行
[[_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);
}];
監(jiān)聽事件
- 監(jiān)聽按鈕點擊事件
[[_btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
NSLog(@"%@", x);
}];
- 監(jiān)聽文本框輸入
[[_tf rac_textSignal] subscribeNext:^(NSString * _Nullable x) {
NSLog(@"%@", x);
}];
代替通知
如監(jiān)聽鍵盤出現(xiàn)
[[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIKeyboardWillShowNotification object:nil] subscribeNext:^(NSNotification * _Nullable x) {
NSLog(@"%@", x);
}];