Search code examples
swiftreactive-programmingswiftbond

Binding textfield text to enable button not working


I am new to reactive programming, and Bond framework specifically. I know I may be doing things that are wrong in my basic understanding of this programming technique. This is the situation:

I have a UITextView and an "approve" UIButton. I want the approve button to be enabled only when the text in the textView is not nil. I have tried adding these lines of code into my viewDidLoad method in my ViewController.

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

The first action works (printing the text is happening successfully on every input change). The second one does not work, the button is enabled both when the text is not nil and when it is.

Any help appreciated.


Solution

  • I found the issue was that I had a placeholder in my textView, which prevented from the text really being nil. So what eventually I did is this:

        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)