ReactiveCocoa 5.0中的RACObserve(object,keyPath)

时间:2016-11-21 01:45:21

标签: objective-c swift swift3 reactive-cocoa reactive-cocoa-5

我想监视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时实现相同的目标,怎么做?

1 个答案:

答案 0 :(得分:4)

enter image description here

使用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)
    }

然而,这并不鼓励,因为

  1. ReactiveCocoa 5.0 will add UIKit Extensions如果它起作用,那只是巧合。
  2. 可以说,你的“真相”不应该在UI /按钮中,但你应该有一个模型确定是否启用了按钮。
  3. 使用模型

    在此示例中,使用简单的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

    直接绑定到按钮标题颜色