9

I have a UITextField but I want to be in control of when it is focussed and when it is unfocussed.

In order to achieve this I need to be able to block touch events on that text field. I know I could just put a button in front of it and manually do it, but I wanted to know if there was any way to just disable touches on the element.

Many thanks.

Thomas Clayson
  • 29,657
  • 26
  • 147
  • 224

3 Answers3

17

There does not appear to be a way to block touches with a property of UITextField. I solved this problem by placing a UIView over the text field to block the touches. I set the UIView to "Clear Color" using the attributes inspector. Works great for my application.

T.J.
  • 3,942
  • 2
  • 32
  • 40
2

How about the userInteractionEnabled property?

borrrden
  • 33,256
  • 8
  • 74
  • 109
  • 1
    That also stops you from inputting text via a keyboard, which I need. I only want to stop touches. Not **all** interaction. :) – Thomas Clayson Feb 05 '13 at 16:00
  • I don't understand...if you disable touches, then the user won't be able to touch it to bring out the keyboard anyway so what's the difference? – borrrden Feb 05 '13 at 23:35
  • But I can manually call `becomeFirstResponder` on it to bring out the keyboard. :) – Thomas Clayson Feb 06 '13 at 09:05
  • 1
    Yeah...and when you do that, just enable user interaction again. – borrrden Feb 06 '13 at 09:16
  • Yes...that is how text input fields work in general. Your question states that you want to "control when it becomes focused and unfocused" and wonder if there is "a way to disable touches on the element." If you need additional behavior, you need to specify that in your question. If you only want keyboard interaction, but no touches still, then that is very unusual and there is no built-in way. – borrrden Feb 07 '13 at 01:09
  • Then thats the answer. :) Thanks for your time. – Thomas Clayson Feb 07 '13 at 09:27
2

I had to have cursor interaction while editing, so before becomeFirstResponder() i set isUserInteractionEnabled = true and on end editing set it on false

@IBAction func editTapped(_ sender: UIButton) {
    textField.isUserInteractionEnabled = true
    textField.becomeFirstResponder()
}


func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
    print(textField.textValue)

    textField.isUserInteractionEnabled = false

    return true
}
Markicevic
  • 1,025
  • 9
  • 20