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.如果使用代理,需要创建一个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);
     }];

监听事件

  1. 监听按钮点击事件
    [[_btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        NSLog(@"%@", x);
    }];
  1. 监听文本框输入
    [[_tf rac_textSignal] subscribeNext:^(NSString * _Nullable x) {
        NSLog(@"%@", x);
    }];

代替通知

如监听键盘出现

    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIKeyboardWillShowNotification object:nil] subscribeNext:^(NSNotification * _Nullable x) {
        NSLog(@"%@", x);
    }];
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容