从今天起关心底层和原理!
Demo链接:https://github.com/asd521411/RAC-ReactiveCocoa.git
cocoapods 导入rac框架
导入头文件
#import <NSObject+RACKVOWrapper.h>
RAC基于信号,类似通知,通过发送信号执行相应方法,响应式编程常见:masonry、afn
\1、基本
- (void)demo {
//1.创建信号
RACSubject *sub = [RACSubject subject];
//2.订阅信号
[sub subscribeNext:^(id _Nullable x) {
NSLog(@“接收信号=====”);
}];
//3.发送信号
[sub sendNext:@“发送信号”];
}
//2、现在自定义一个view,view里面有个button,外面引用的时候执行button方法通常代理或者block,现在用RA
C实现,如下:
新建一个CustomView,继承于View
custom.h
#import <UIKit/UIKit.h>
#import <ReactiveObjC.h>
@interface CustomView : UIView
@property (nonatomic, strong) RACSubject *subject;
@end
custom.m里面===================
#import “CustomView.h”
@interface CustomView()
@property (nonatomic, strong) UIButton *customBtn;
@end
@implementation CustomView
-
(instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.customBtn = [UIButton buttonWithType:UIButtonTypeCustom];
self.customBtn.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
//self.customBtn.backgroundColor = [UIColor cyanColor];
self.customBtn.center = self.center;
[self addSubview:self.customBtn];
[self.customBtn addTarget:self action:@selector(customBtnTouch:) forControlEvents:UIControlEventTouchUpInside];
}
return self;
} -
(void)customBtnTouch:(UIButton *)btn {
[self.subject sendNext:@“发送”];
}
//懒 -
(RACSubject *)subject {
if (_subject == nil) {
_subject = [RACSubject subject];
}
return _subject;
}
ViewController.m里调用 -
(void)demo1 {
CustomView *custom = [[CustomView alloc] initWithFrame:CGRectMake(0, 100, 100, 40)];
[self.view addSubview:custom];
[custom.subject subscribeNext:^(id _Nullable x) {
NSLog(@“接受消息=======%@”, x);
}];
}
//3、更简洁的方式,直接观察button的方法名
- (void)demo2 {
CustomViewOther *other = [[CustomViewOther alloc] initWithFrame:CGRectMake(0, 200, 100, 40)];
other.backgroundColor = [UIColor orangeColor];
[self.view addSubview:other];
//通过方法名观察
[[other rac_signalForSelector:@selector(customBtnOtherTouch:)] subscribeNext:^(RACTuple * _Nullable x) {
NSLog(@“观察按钮点击===============%@”, x);
}];
//通过事件类型
[[other.customBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
NSLog(@“事件”);
}];
}
//4、实时观察textfield 的输入
-
(void)demo3 {
UITextField *field = [[UITextField alloc] initWithFrame:CGRectMake(0, 300, 100, 40)];
field.backgroundColor = [UIColor purpleColor];
[self.view addSubview:field];UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(120, 300, 100, 40)];
label.backgroundColor = [UIColor cyanColor];
[self.view addSubview:label];
//1、
[field.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
NSLog(@“实时监听输入=====%@”, x);
label.text = x;
}];//2、同1,更简洁,用来给某个对象的某个属性绑定信号,只要产生信号内容,就会把内容给属性赋值
RAC(label,text) = field.rac_textSignal;
//监听的宏
[RACObserve(label, frame) subscribeNext:^(id _Nullable x) {}];
}
demo地址: