代替代理
1.自定義一個(gè)View控件,并添加一個(gè)按鈕
- (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.如果使用代理糕再,需要?jiǎng)?chuàng)建一個(gè)delegate屬性钉迷,在clickButton:中執(zhí)行[self.delegate xxx],并在vc中實(shí)現(xiàn)代理方法庐完。
3.但通過(guò)RAC就方便許多裆蒸,直接在VC中添加自定義view
@property (nonatomic, strong) MyView *v;
4.要接收點(diǎn)擊事件直接執(zhí)行
[[_v rac_signalForSelector:@selector(clickButton:)] subscribeNext:^(RACTuple * _Nullable x) {
NSLog(@"%@", x);
}];
5.運(yùn)行結(jié)果如圖:
運(yùn)行結(jié)果
代替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)聽(tīng)事件
- 監(jiān)聽(tīng)按鈕點(diǎn)擊事件
[[_btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
NSLog(@"%@", x);
}];
- 監(jiān)聽(tīng)文本框輸入
[[_tf rac_textSignal] subscribeNext:^(NSString * _Nullable x) {
NSLog(@"%@", x);
}];
代替通知
如監(jiān)聽(tīng)鍵盤出現(xiàn)
[[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIKeyboardWillShowNotification object:nil] subscribeNext:^(NSNotification * _Nullable x) {
NSLog(@"%@", x);
}];