I have a textfield
and a textView
in my UIViewController
and in my ViewModel
I have two String
variable, I want to bind the textField
to variabletitle
and the textView
to variable textBody
. In RAC2 it's straight forward with RAC but what about RAC4 and Swift2 ?
I found this in StackOverFlow :
let producer = textField.rac_textSignal().toSignalProducer()
.flatMapError { error in
return SignalProducer<AnyObject?, NoError>.empty
}
.map { text in Int(text as! String) }
self.viewModel.title <~ producer
but I get Use of undeclared type 'NoError'
so I changed it to NSError
but now I get : Binary operator '<~' cannot be applied to operands of type 'String' and 'SignalProducer<Int?, NSError>' (aka 'SignalProducer<Optional<Int>, NSError>')
self.viewModel.title
is a simple var title = ""
I know that I can do that :
textField.rac_textSignal()
.toSignalProducer()
.map { text in text as! String } // AnyObject -> String
.filter { string in string.characters.count > 0 } // String -> Bool
.startWithNext { [weak self] (text) in
self?.viewModel.title = text
}
but why all that code to just bind and the use of startWithNext
and [weak self]
:(
Swift does not have macro or KVC in objects, so there is no binding magic like RAC()
. Bindings in Swift are intended to target Property
types.
P.S. You may need import enum Result.NoError
for the NoError
type.
In ReactiveCocoa 5.0, primitives like reactive.text
and reactive.textValues
are provided in various UIKit/AppKit controls and views.
textField.text <~ viewModel.title.producer
viewModel.title <~ textField.textValues
Although we do not have a bidirectional binding system in ReactiveCocoa yet, the above snippet would work without an infinite feedback loop.
This only works for bindings with controls though. Bidirectional bindings between properties, if you ever need it, are impossible without a mediator in between.
@andersio I鈥檝e seen that you started the work on support for bidirectional bindings on MutableProperty
in ReactiveCocoa/ReactiveSwift#181 and ReactiveCocoa/ReactiveSwift#182 a couple of years ago. Are there any plans to continue at some point, or is this kind of binding out of scope for ReactiveCocoa/ReactiveSwift? I鈥檓 just curious to hear an update on that since I run into this problem quite often, and it always brings me to this GitHub issue. 馃槈
Most helpful comment
In ReactiveCocoa 5.0, primitives like
reactive.text
andreactive.textValues
are provided in various UIKit/AppKit controls and views.Although we do not have a bidirectional binding system in ReactiveCocoa yet, the above snippet would work without an infinite feedback loop.
This only works for bindings with controls though. Bidirectional bindings between properties, if you ever need it, are impossible without a mediator in between.