1

Newbie to ReactiveCocoa and ReactiveSwfit here... Sorry if the answer is obvious.

I am trying to adapt the Start Developing iOS Apps with Swift sample to ReactiveSwift / ReactiveCocoa, and I am running into an issue with "translating" the UITextField's Delegate method -- which gets rid of the keyboard and essentially ends the editing (so I can capture the text field in the mealNameLabel) :

  • func textFieldShouldReturn(_ textField: UITextField) -> Bool

I am using

    nameTextField.reactive.textValues.observeValues { value in
        viewModel.mealName.swap(value ?? "")
    }

    // Setup bindings to update the view's meal label
    // based on data from the View Model
    mealNameLabel.reactive.text <~ viewModel.mealLabel

to get the value from the text field into the view model and percolate the view model's label back to the UILabel (convoluted...)

That works fine, as long as I maintain the viewController as the UITextField's delegate and I still implement the method depicted in the tutorial and mentioned above. Essentially :

override func viewDidLoad() {
    super.viewDidLoad()

    nameTextField.delegate = self
    // view controller logic
    ...
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    // Hide the keyboard.
    textField.resignFirstResponder()
    return true
}

I tried using

nameTextField.reactive.controlEvents

but that failed miserably due to my lack of understanding of controlEvents (docs anywhere ?).

So what do I need to do to make the keyboard disappear when the user is done editing, the "reactive way" ?

Thanks !!!

Nick
  • 321
  • 3
  • 16

1 Answers1

1

(Of course right after I post my question...)

It looks like this might actually do the trick :

    nameTextField.reactive.controlEvents(UIControlEvents.primaryActionTriggered)
        .observeValues { textField in
        textField.resignFirstResponder()
    }

After fiddling with the different event types, it looks like .primaryActionTriggered is what gets triggered when the "Done" button is pressed.

Any better way to do this ?

Nick
  • 321
  • 3
  • 16
  • I would use `editingDidEnd` instead of `primaryActionTriggered`. – Sebastian Hojas May 25 '17 at 12:04
  • @SebastianHojas : I tried with .editingDidEnd initially but that didn't seem to work (both on the simulator and the device directly). By observing that event I can actually see that it's triggered after the keyboard is dismissed (weird ?). – Nick May 25 '17 at 14:12