Dismissing keyboard in UITextField with RAC(5)?

435 Views Asked by At

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 !!!

1

There are 1 best solutions below

2
Nick On

(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 ?