绑定文本字段文本以使按钮不起作用

时间:2017-08-22 08:49:06

标签: swift reactive-programming swiftbond

我是反应式编程的新手,特别是Bond框架。我知道我可能会在我对这种编程技术的基本理解中做错了。情况就是这样:

我有一个UITextView和一个"批准" UIButton。 我希望只有当textView中的文本不是nil时才启用批准按钮。我已尝试将这些代码行添加到viewDidLoad中的ViewController方法中。

    textView.reactive.text.observeNext{(text) in
        self.message = text
        print(text)
    }
    textView.reactive.text.map { $0 != nil}.bind(to: approveButtonOutlet.reactive.isEnabled)

第一个动作有效(在每次输入更改时都会成功打印文本)。 第二个不起作用,当文本不是nil时,按钮都被启用。

任何帮助表示感谢。

2 个答案:

答案 0 :(得分:1)

您可以尝试

 RAC(self.approveButtonOutlet, enabled) = [self.textView.rac_textSignal map:^id(NSString *text) {
      return @(text.length > 0);
    }];

我不确定它在swift 3中会如何尝试

RAC(self.approveButtonOutlet, enabled) = self.textView.rac_textSignal.map({(text: String) -> void in
    return (text.length > 0)
})

答案 1 :(得分:0)

我发现问题是我在textView中有一个占位符,它阻止文本真正为零。所以最终我做的是:

    textView.reactive.text.map {
        if $0 == placeholder {
            return false
        } else if $0 != nil {
            return $0!.characters.count > 0
        } else{
            return false
        }
        }.bind(to: approveButtonOutlet.reactive.isEnabled)