How to Use UITextField in iPhone Programming

Matthew Campbell, October 5th, 2009

Here is the standard way of getting user input and then using the input in your app.

UITextField works with the delegation pattern in Objective-C. That is, you need to designate an object to act “on behalf” of the text field object. In this video I show you how to use the UITextField to ask a user for input and then post the results to a label.

NOTE: The code in the video would cause a memory leak because the label and text field where not released after being added to the subview collection (take a close look)… See the code box below for the complete non-leaky code.

Here is the code from the example:

The first thing we needed to do was indicate that our view controller would be acting as a delegate for the UITextField. To do this you simply need to declare it in the interface file:

This part is straightforward enough: you essentially create a label and a text field and add them both to the view controller’s subview collection. This is the typical pattern used to build up a view in code.

I didn’t bother highlighting here because the entire block of code is needed to create the two objects.

This is the part that is fuzzy for most new iPhone programmers so please bear with me. Your UITextField object called textField above was added to the subview collection of the view controller we are essentially writing our code in. This view controller is capable of being a delegate for any text field because we indicated as much in the interface file. Furthermore, our view controller will serve as a delegate to our UITextField object, textField, because we set textField’s delegate property to the view controller by using the “self” keyword.

So, what this all means is that now our view controller will act on behalf of textField. So, our view controller will intercept and respond to events such as user’s starting to edit. Generally, when using text fields we need to be able to respond when the user touches the “Return” key. We do this by implementing a delegate method called textFieldShouldReturn in whatever object is serving as the delegate for the text field. In this case, it is our view controller.

This delegate method activates when the user touches the return button. It does two important things: assigned the label’s text property to the value that the user input and it dismisses the keyboard.

That is how to use a text field to get input. For new iPhone programmers the pattern of delegate seems odd, but it does add some flexibility since the alternative could have required us to create an entire new subclass of UITextField to respond to the user events we need. Regardless, delegation is something that you should spend some time wrapping your head around since it is used often in iPhone programming and Objective-C in general.