objective-c - ReactiveCocoa 5.0 中的 RACObserve(object, keyPath)

标签 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 在 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)
    }

然而,这是不被鼓励的,因为

  1. UIKit does not comply to KVO如果它有效,那只是巧合。
  2. 可以说,您的“真相”不应该在用户界面/按钮中,但您应该在某个地方有一个模型来确定按钮是否启用。

有模型

在这个例子中,一个简单的 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

那样直接绑定(bind)到按钮标题颜色

关于objective-c - ReactiveCocoa 5.0 中的 RACObserve(object, keyPath),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40711642/

相关文章:

iphone - 这里需要 "atomic"吗?

ios - 如何将网址重定向到Soundcloud或youtube应用(如果已下载)

ios - 允许登录类在全局拥有一个共享实例

ios - 根据设备区域设置格式化日期字符串

ios - Objective-C - 推送通知不适用于 Cloudkit

Swift - 结构或字典

ios - 如何向 UIBarButtonItem 添加字母间距?

快速使用 map 设置属性

ios - 如何在 Swift 3 的字符串文字中表示特殊字符

iOS Facebook SDK 在我拥有管理员权限的页面上发布图片