0

I have a UITextField and in my ViewController's code it is set depending on it's value to

textField.isUserInteractionEnabled = false

or

textField.isUserInteractionEnabled = true

Now, when user interaction is disabled, I would like it still to react to touches and show an error message (e.g. unhide another view), which tells the user that editing this text field is not possible.

How can I achieve this in the most lean way? This solution here (https://stackoverflow.com/a/9117285) suggests to not disable user interaction, but reject content changes - which is what I don't want (the keyboard should not show up - it won't show up when user interaction is disabled, but I can't react to touches either).

Pauli
  • 343
  • 1
  • 4
  • 17

2 Answers2

0

You either need to add a view a bove the textfield when it's disabled with a gesture to show the appropriate message , or do this

 NotificationCenter.default.addObserver(self, selector: #selector(keyShow), name:UIResponder.keyboardWillShowNotification, object: nil)

} 
@objc func keyShow ( _ not:NSNotification) {

    if shouldHideKeyB {

        self.view.endEditing(true)

        // show disabled message 
    }

}

where shouldHideKeyB is the current state of the textfield

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
  • That's not exactly what I am looking for. If I set isUserInteractionEnabled = false then the keyboard doesn't show up (like it is desired). However, I cannot receive touches for showing the view with the error message. – Pauli Dec 30 '18 at 12:25
  • @Pauli don't set it to `isUserInteractionEnabled` , create a var named `shouldHideKeyB` and manage that like above – Shehata Gamal Dec 30 '18 at 12:31
0

Instead of using isUserInteractionEnabled you could implement your own isDisabled Bool and UITextFieldDelegate and implement func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool. When isDisabled is true show the error view and return false, otherwise return true. In the didSet of isDisabled you can hide the error view.

Returning false from this method should stop the keyboard from popping up and will still allow you to interact with the view.

hartwellalex
  • 396
  • 3
  • 3