我在OC这样做过:
#import "ViewController.h"
#import <ReactiveCocoa/ReactiveCocoa.h>
@interface ViewController () <UITextViewDelegate>
@property (weak, nonatomic) IBOutlet UIButton *btn;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self initUI];
}
- (void)initUI {
__weak typeof(self) weakSelf = self;
[[RACObserve(self.btn, enabled) map:^id(id value) {
return [value boolValue] ? [UIColor greenColor] : [UIColor redColor];
}] subscribeNext:^(id x) {
[weakSelf.btn setTitleColor:x forState:UIControlStateNormal];
}];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
self.btn.enabled = !self.btn.enabled;
}
@end
现在,我尝试在快速使用最新版本的ReactiveCocoa时实现相同的目标,怎么做?
答案 0 :(得分:4)
button.reactive.values(forKeyPath:)
这适用于简单的游乐场:
button.reactive.values(forKeyPath: "enabled")
.map { $0 as? Bool }
.skipNil()
.map { enabled in enabled ? UIColor.blue : UIColor.red }
.startWithValues { [weak button = button] color in
button?.setTitleColor(color, for: .normal)
}
然而,这并不鼓励,因为
在此示例中,使用简单的MutableProperty
作为模型,这可以在ViewModel中或任何位置
let buttonEnabled = MutableProperty<Bool>(false)
button.reactive.isEnabled <~ buttonEnabled
buttonEnabled.producer
.map { enabled in enabled ? UIColor.blue : UIColor.red }
.startWithValues { [weak button = button] color in
button?.setTitleColor(color, for: .normal)
}
不幸的是,您无法使用isEnabled