UITextField – A Complete API Overview

  • Twitter
  • Facebook
  • Digg
  • Reddit
  • StumbleUpon
  • del.icio.us
  • Google Bookmarks
January 4th, 2010 Posted by: (ELC) - posted under:Tutorials

The UITextField is probably one of the most commonly used UI controls on the iPhone. It is the primary method of user input via the keyboard and provides a great deal of additional functionality.

With the success of our las API tutorial on NSArray, I thought I would do another walkthrough, this time on UITextField. I will be explaining all of the properties for it as well as bringing up some functionality that you may not have known about.

Text Attributes

The attributes have to do with the actual text inside of the UITextField.

text The text displayed in the UITextField
placeholder The text that gets displayed prior to the user entering in anything. This text is usually a lighter color than the primary text to denote that it will be replaced.
font The font of the text to be displayed. You can set it like this
textColor The color of the text that is displayed
textAlignment How the text is aligned in the UITextField. The possible values for this are UITextAlignmentLeft, UITextAlignmentRight, UITextAlignmentCenter

Here are some examples of using these properties.

// Setting the text
[myTextField setText:@"This is some text!"];
 
// Setting the placeholder
[myTextField setPlaceholder:@"Type text here"];
 
// Setting the font.
[myTextField setFont:[UIFont fontWithName:@"Times New Roman" size:14]];
 
// Setting the text color
[myTextField setTextColor:[UIColor blueColor]];
 
// Setting the text alignment
[myTextField setTextAlignment:UITextAlignmentCenter];

Here is what the UITextField would look like after we update these properties.


Adjusting the size of the text in the UITextField

The text displayed in our UITextField can be dynamically sized based on the width of the UITextField. The benefit of this is all of the text being typed will be visible on the screen. It will shrink the text down until it reaches the default font size of 17. So, for this to make sense, you must set the font size of the UITextField to something larger than 17.

adjustsFontSizeToFitWidth Boolean value denoting whether to fit the font size to the width of the UITextField.

Here is an example of using these properties.

[myTextField setFont:[UIFont fontWithName:@"Times New Roman" size:30]];
[myTextField setAdjustsFontSizeToFitWidth:YES];

Here are some screenshots of the text shrinking when typing in the UITextField.


Managing the editor’s behavior

These two properties are pretty straight forward.

editing Read-only boolean value letting you know if the user is currently editing the UITextField
clearsOnBeginEditing Clears the text in the field every time the user begins to edit it.

Not very exciting and probably doesn’t even deserve an example…

Setting the view’s background appearance

This group of properties defines how the UITextField will look. If you have ever seen a fancy input box, this is how they are doing it.

borderStyle Defines the type of border for the UITextField. Possible choices are UITextBorderStyleNone, UITextBorderStyleLine, UITextBorderStyleBezel, and UITextBorderStyleRoundedRect. The default is UITextBorderStyleNone.
background A UIImage representing the background image of the UITextField when it’s enabled. If this field is altered the borderStyle property is ignored.
backgroundDisabled A UIImage representing the background image of the UITextField when it’s disabled.

Here is are some example of using each of the border styles

// Border Style None
[myTextField setBorderStyle:UITextBorderStyleNone];

// Border Style Line
[myTextField setBorderStyle:UITextBorderStyleLine];

// Border Style Bezel
[myTextField setBorderStyle:UITextBorderStyleBezel];

// Border Style Rounded Rect
[myTextField setBorderStyle:UITextBorderStyleRoundedRect];

The border style is not terribly exciting. However, you can really spruce up your UITextFields using the background property. Here is an example of setting the background property to this image.

myTextField.textAlignment = UITextAlignmentCenter;
myTextField.textColor = [UIColor whiteColor];
myTextField.borderStyle = UITextBorderStyleNone;
myTextField.background = [UIImage imageNamed:@"bg.png"];

and the result… Looks pretty good ehh? One GOTCHA that I want to point out here is, to get the background property to work correctly, you must set the boderStyle to anything other than UITextBorderStyleRoundedRect. Otherwise, the default UITextField will be displayed.
Setting the view’s background appearance

Managing Overlay Views

Another interesting way of customizing your UITextFields is to use an overlay. UITextField offers a left and right overlay for your UITextFields. Here are the properties:

clearButtonMode The circled X that gets displayed when typing. Used to clear out the text. Possible values: UITextFieldViewModeNever, UITextFieldViewModeWhileEditing, UITextFieldViewModeUnlessEditing, UITextFieldViewModeAlways
leftView The view that appears to the left inside a UITextField. This could be something like a magnifying glass for search.
leftViewMode Works like clearButtonMode, but toggles the leftView.
rightView Same as leftView, except it aligns to the right.
rightViewMode Same as leftViewMode but controls the rightView

Let’s take a look at how adjusting the leftView works:

UIImageView * myView = [[ UIImageView  alloc ]  initWithImage :
		[UIImage  imageNamed : @"wordpress.png" ]];
[myTextField  setLeftView :myView];
[ myTextField   setLeftViewMode: UITextFieldViewModeAlways];
[myView release ];

As you can see, the text aligns after the image. This is a very simple way to really spruce up your UITextFields.

The last thing we are going to discuss is showing and hiding the keyboard.

Showing and Hiding The Keyboard

To show the keyboard:

[myTextField becomeFirstResponder];

To hide the keyboard

[myTextField resignFirstResponder];

Well, I hope you have enjoyed this tutorial on the UITextField.  I would love to see links to some interesting custom UITextFields in the comments, so please post them.  Thanks for reading and happy iCoding!

  • iPortable

    thank you, it’s only basics but you have invested time in it so thanks :)

  • http://RTHilton.com RTHilton

    Great tutorial, just once bit of criticism. Isn’t it blasphemy to use Times New Roman on anything? I know my graphic designer always shudders when I leave things as the defaults and don’t change my fonts immediately to a pretty sans font.

    Keep it up, I will definitely be subscribing.

  • aong

    Thank you, for best tutorial.

  • http://www.imanapp.com Glenn

    Great overview!
    I’d like more of these with different api’s..

    Only bad thing is indeed the use of times new roman :P

  • http://brandontreb.com brandontreb

    hahaha Times New Roman is terrible. It was just the only other font I could think of off the top of my head besides helvetica. I guess Verdana would have been a better choice.

  • salomoko

    Myriad Pro yo!

  • Franck

    Hi Brandon,
    Thanks for this tutorial. Icodeblog definitely rocks.
    I have one question for you: I use a UITextField to update my datas, but there’s smth I can’t seem to figure out:
    what is the difference between the “did end on exit” and the “editing did end”? right now I have connected those two events to the same ibaction because I wanted to perform the action when the user pressed return as well as when he clicks the search button, but this way I end up performing the action twice… Which one should I use, and when?
    More importantly, how do you find documentation about that? Searching the documentation for “value changed” I cannot find more info on that event notification…
    Thanks in advance for your help,
    Keep up the good work!
    Franck

  • Toni

    > The font of the text to be displayed. You can set it like this

    Set it like what????

  • Jane

    > Showing and Hiding The Keyboard

    You need to tell *WHERE* to put that code… not just show the code line.

  • http://www.devapp.it/wordpress/uitextfield-guida-completa-all-uso-by-icodeblog.html UITextField – Guida completa all’uso (by iCodeBlog) | devAPP

    [...] ringraziamento a brandontreb di iCodeBlog per questa utile e completa guida sull’UITextField. L’UITextField è probabilmente uno [...]

  • Antonio

    Thanks for the great article, very informative and worth of bookmarking for future reference!

    @Jane: There are better ways to ask for something, specially when you are clueless on the subject. Asking where to put the code to show/hide the keyboard is like asking what color you should use on the background of your textfield. It’s something particular to *your* software, eg.: you click on a button and you want the action to be to hide the keyboard so the UI has more screen space.

  • http://techbars.com ariauakbar

    wow, this is great dude. very complete!

  • AD

    Where do you put:

    [myTextField becomeFirstResponder];
    [myTextField resignFirstResponder];

    I tried putting them one after the other in my viewDidLoad function, but it gives unexpected results.

    Any help on this would be great

  • http://www.examiner.com/x-45117-Mobile-Media-Exami Nick

    How do you use the “Next” button on the keyboard to tab between text fields.

  • http://TryFirst.nl Pettrie de Bondt

    Nice tutorial, really like the way you walked trough it.
    for the next button to work, add the delegate:
    - (BOOL)textFieldShouldReturn:(UITextField *)textField {
    }
    Inside this field, use
    [currentField resignFirstResponder];
    [newField becomeFirstResponder];
    To select the newField for the text input
    greetz

  • Shai

    For some reason the alignment is not working.
    the text is left aligned based on the language default.
    Any suggestions?

  • Shai

    The Alignment is not working if the text is not set in the code. My text was based on what I’ve places in the xib file. Once I’ve populated the text in the code is started to work. 

  • vvk

    Hey it was a really useful post… Thanks

  • paii

    Thanks for your post

  • Piotr

    Is there possibility to hide textfield cursor while editing?

  • http://twitter.com/dipakdobariya dipak dobariya

    Hello,
    I like your tutorial it’s tooooooo nice….
    Have any Idea “How to change the PlaceHolder color?”

    Thanks,
    David.

  • Jeff

    Thanks for the info. Solved a question I have had for a while. One question. Where is the best place to set the properties of ui objects like the text field?

  • Adnan Ahmad

    very nice post

blog comments powered by Disqus