RAC是一个很常用并且很好用的插件,简洁的调用方式可以代替很多原生方法,下面是RACSubject代替通知的使用方式:
#import <UIKit/UIKit.h> #import <ReactiveObjC.h> NS_ASSUME_NONNULL_BEGIN @interface LWView : UIView @property (nonatomic,strong)RACSubject * notifiSignal; @end NS_ASSUME_NONNULL_END #import "LWView.h" @implementation LWView - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { [self setupUI]; self.backgroundColor = [UIColor redColor]; } return self; } - (void)setupUI{ UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom]; btn.frame = self.bounds; [btn addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside]; [self addSubview:btn]; }
- (void)click{
[self.notifiSignal sendNext:nil];
}
视图内添加了一个按钮,按钮点击时触发点击事件,我们在viewController内使用视图并接收通知
- (void)setupUI{ LWView *view = [[LWView alloc] initWithFrame:CGRectMake(0, 300, self.view.frame.size.width, 300)]; view.notifiSignal = [RACSubject subject]; [view.notifiSignal subscribeNext:^(id _Nullable x) { //点击按钮需要处理的事即可写在此处 }]; [self.view addSubview:view]; }
这样就实现了RACSubject代替了通知