我想监听 UIButton.enabled 属性来改变 button.titleColor
我在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 在 swift 中实现相同的目标,该怎么做?
最佳答案
ReactiveCocoa 5.0 will add UIKit Extensions .
使用 button.reactive.values(forKeyPath:)
这在一个简单的 Playground 中对我有用:
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)
}
然而,这是不被鼓励的,因为
- UIKit does not comply to KVO如果它有效,那只是巧合。
- 可以说,您的“真相”不应该在用户界面/按钮中,但您应该在某个地方有一个模型来确定按钮是否启用。
有模型
在这个例子中,一个简单的 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
关于objective-c - ReactiveCocoa 5.0 中的 RACObserve(object, keyPath),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40711642/