RAC常見應用場景

代替代理

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)聽事件

  1. 監(jiān)聽按鈕點擊事件
    [[_btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        NSLog(@"%@", x);
    }];
  1. 監(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);
    }];
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容