Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I respond to touch events on a UITextField?

I want to respond to touch events (specifically UIControlEventTouchUpInside and UIControlEventTouchUpOutside) on a UITextField, but the only event that comes through is UIControlEventTouchCancel.

I can't use UIControlEventEditingDidBegin, because it only occurs when field gains focus, which is not what I'm trying to detect. I want to know when the user lifts their finger, and whether it was inside or outside the text field, regardless of current focus state.

Does anyone know a way to accomplish this?

To be clear I've tried using addTarget:action:forControlEvents and it does not work. The touch up event is prevented by the cancel. I want a way to detect the touch up before the UITextField consumes it and produces the Cancel event.

Also, I'd like to avoid creating any extra views if possible.

like image 623
theK42 Avatar asked Jan 10 '12 02:01

theK42


2 Answers

Well a round about way of doing it would be to create a UIButton with the fill set to clear to cover all of the space, and a UITextField on top of it. If the user touches in the text field, the text field should send an event, and if the user touches outside of the text field, the UIButton will send the event.

like image 147
brandonbocklund Avatar answered Nov 15 '22 17:11

brandonbocklund


Good answer here: Change default touch events for UITextField

Use the text field's delegate and do what you want to do in textFieldShouldBeginEditing:

You can return NO to prevent the default behavior.

like image 31
beev Avatar answered Nov 15 '22 17:11

beev