ReactiveCocoa(RAC)学习

前端之家收集整理的这篇文章主要介绍了ReactiveCocoa(RAC)学习前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

开发中ReactiveCocoa(RAC)常见用法


RAC监听按钮点击事件

[[self.button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
    NSLog(@"RAC检测按钮点击");
}];
//或者:
self.button.rac_command = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
    NSLog(@"RAC检测按钮点击2");
    return [RACSignal empty]; //返回空信号
}];

RAC监听手势

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
[[tap rac_gestureSignal] subscribeNext:^(id x) {
    NSLog(@"RAC检测手势");
}];
self.imageView.userInteractionEnabled = YES;
[self.imageView addGestureRecognizer:tap];

RAC遍历数组 / 字典

//遍历数组
NSArray *array = @[@1,@3,@55,@76,@56,@45];

//1>把数组转换成集合RACSequence array.rac_sequence
//2>把集合RACSequence转换RACSignal信号类,array.rac_sequence.signal
//3>订阅信号,激活信号,会自动把集合中的所有值,遍历出来。
[array.rac_sequence.signal subscribeNext:^(id x) {
    NSLog(@"RAC遍历数组元素:%@",x);
}];

//遍历字典
NSDictionary *dict = @{@"name":@"stevin",@"location":@"Beijing"};
//RACTuple:元组类,类似NSArray,用来包装值.
//RACSequence:RAC中的集合类,用于代替NSArray,NSDictionary,可以使用它来快速遍历数组和字典。
[dict.rac_sequence.signal subscribeNext:^(RACTuple *x) {
    //解包元组,会把元组的值,按顺序给参数里面的变量赋值
    RACTupleUnpack(NSString *key,NSString *value) = x;
    NSLog(@"RAC遍历字典键值:%@--%@",key,value);
}];

RAC观察值改变

//监听本类属性string值得变化并打印
[RACObserve(self,string) subscribeNext:^(NSString *string) {
    NSLog(@"RAC检测值改变:%@",string);
}];

RAC监听UITextField输入

[self.textFieldName.rac_textSignal subscribeNext:^(id x) {
    NSLog(@"RAC监听TextField输入:%@",x);
}];
[[self.textFieldName.rac_textSignal filter:^BOOL(id value) {
    NSString *text = value;
    //只有当文本框的内容长度大于3,才获取文本框里的内容
    return text.length > 3;
}] subscribeNext:^(id x) {
    NSLog(@"RAC检测到输入了长度大于3的内容:%@",x);
}];

RAC代替代理Delegate

[[self rac_signalForSelector:@selector(tableViewCell:buttonClick:) fromProtocol:@protocol(TableViewCellDelegate)] subscribeNext:^(id x) {
    NSLog(@"RAC代理响应成功");
}];

RAC观察通知Notification

[[[NSNotificationCenter defaultCenter] rac_addObserverForName:NotificationName object:nil] subscribeNext:^(NSNotification *notification) {
    NSLog(@"RAC通知响应成功:%@",notification.userInfo);
}];

RAC监听方法调用

[[self rac_signalForSelector:@selector(tableView:numberOfRowsInSection:)] subscribeNext:^(id x) {
    NSLog(@"tableView:numberOfRowsInSection:被调用!");
}];

猜你在找的React相关文章