0

The following is a snippet of tutorial code that binds a toggle switch to an activity indicator:

 aSwitch.rx.value
    .map { !$0 }
    .bind(to: activityIndicator.rx.isHidden)
    .disposed(by: disposeBag)

 aSwitch.rx.value.asDriver()
    .drive(activityIndicator.rx.isAnimating)
    .disposed(by: disposeBag)

What is the syntax of binding to a private func()?
I want to be able to several things beyond merely flipping a boolean value.

Specifically, I would like to:

  1. Toggle the title of another button;
  2. Enable & clear a UITextView; and
  3. Change a UILabel text.

Or is it better in this case, to merely use the familiar toggle-button @IBAction paradigm?

Frederick C. Lee
  • 9,019
  • 17
  • 64
  • 105

1 Answers1

0

If the title of another button is dependent on the value of your UISwitch, then you should do something like:

let buttonText = aSwitch.rx.value.map { $0 ? "Button is on" : "Button is off" }

and then bind (or drive, if you're using Driver) your button.rx.title to the this Observable. A similar approach is needed for things like clearing a UITextView or changing the text on a label.

If your UIView elements depend on more than just the state of your toggle, then a more complex structure is needed than simply using map, e.g. by using withLatestFrom, combineLatest or other operators (see: http://www.rxmarbles.com). Since this introduces a bunch of new complexity, is it common to contain this logic in a so-called ViewModel. There are plenty of articles detailing how a so-called MVVM pattern works with rxSwift.

RamwiseMatt
  • 2,717
  • 3
  • 16
  • 22