For entering text into your applications, the iPhone SDK provides two classes, UITextField and UITextView. Both allow the user to enter and edit text using an onscreen keyboard and support features such as cut/copy and paste, spell check, and more, but the two classes function differently.
To create a text field:
- You can use the UITextField class to enter small amounts of text, such as user names, passwords, or search terms. This field is limited to a single line of text.
As with most other views, you use the initWithFrame: method to create them:
CGRect textRect = CGRectMake (10,10,300,20); UITextField *myTextField = [[UITextField alloc] initWithFrame:textRect]; myTextField.backgroundColor = [UIColor whiteColor];
This also sets the background color of the text field; otherwise, it's transparent by default.Text fields also don't have a border by default.
Use the borderStyle property to choose from four different styles (Figure 4.30).
The UITextBorderStyleRoundedRect style has a white background and will ignore the backgroundColor property. If you set a custom UIImage as the background, the borderStyle property will be ignored.
Figure 4.30 Border styles available for text fields.
You can set the text font, color, and alignment to apply to the entire text field.
Text fields do not support the styling of individual text elements.
You can set your text field to automatically resize the font to accommodate larger text:
myTextField.font = [UIFont systemFontOfSize:22.0]; myTextField.adjustsFontSizeToFitWidth = YES; myTextField.minimumFontSize = 2.0;
This example sets the initial font size as 22 and then tells the text field to automatically shrink the font to a minimum size of 2 if the text is wider than the text field's bounds.
Setting the clearsOnBeginEditing property to YES will clear any existing text when you first touch the control:
myTextField.clearsOnBeginEditing = YES; myTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
The clearButtonMode property adds a small button to the end of the text field, letting you clear the text at any time (Figure 4.31). You can determine when this button is shown, such as only when editing the text.
Figure 4.31 Press the clear button to remove any text in the text field.
To use keyboards:
- Tap in the text field to open a keyboard from the bottom of the screen.
- You can choose from a number of keyboard styles (Figure 4.32), each designed for particular situations such as entering numbers or using a web browser.
Figure 4.32 Two of the keyboards available by setting the keyboardType property of a text field.
Set the style with the keyboardType property.
By default, the keyboard will automatically suggest words as you type.
- To disable this function, set the autocorrectionType property to UITextAutocorrectTypeNo.
- Set the autocaptializationType property to determine whether the keyboard capitalizes your typing by word, sentence, or even all characters.
- You can change the text on the Return key via the returnKeyType property.
Use the enablesReturnKeyAutomatically property to determine whether the Return key is enabled even if you haven't entered any text into the text field.
In Code Listing 4.23, the secureTextEntry property is set to YES, which is useful for text fields that contain passwords or other sensitive information. As you enter text, you will see only the last letter typed.
Code Listing 4.23 Creating a secure text field.
- You may have noticed that the keyboard doesn't disappear when you press the Return key. To hide the text field, you must implement the textFieldShouldReturn: delegate and tell the text field to resign its first responder status:
[textField resignFirstResponder]; return YES;
- Similarly, you can make the keyboard appear automatically when the view is loaded by setting the first responder status in the viewDidLoad: method:
- To prevent the keyboard from showing at all, which is useful if you are implementing your own custom keyboard, return NO from the textFieldShouldBeginEditing: delegate method.
You can also use the delegate methods to control the text being entered into the text field. The textField:shouldChangeCharactersInRange:replacementString: delegate is called whenever the text is changed. You could, for example, use this method to restrict the number of characters entered. Code Listing 4.24 shows a text field that allows a maximum of ten characters.
Code Listing 4.24 Limiting the contents of a text field to ten characters.
You should check the length of the replacement rather than just looking at the length of the text in the text field, since the text field's contents can be altered via copy and paste as well as by using the keyboard.
For the same reason, simply changing the keyboard type to numeric does not guarantee that a user will enter only numeric values (since a user could paste non-numeric values into the field). Code Listing 4.25 shows the same delegate method, this time restricting the text field to allow numeric values only.
Code Listing 4.25 Restricting the contents of a text field to numeric values.
The UITextView class allows for multiline editable text. Although similar to text fields, text views feature a number of important differences.
Text views don't have any support for automatically reducing the font size like text fields have. Also, they don't have any support for clearing the text other than through programmatically setting the text property. There is also no support for secure text entry.
As with text fields, text views also apply the same text style to the entire text. Apple recommends using a UIWebView (see the "Web Views" section) if you require multiple styles in your text.
Text views can analyze their contents and convert any links or phone numbers into tappable links by using a capability known as data detectors. Tapping the link will either launch the browser or call the phone number.
Two data detector types are available: UIDataDetectorTypePhoneNumber for phone numbers and UIDataDetectorTypeLink for Web http: links. To enable both, set the dataDetectorTypes property:
myTextView.dataDetectorTypes = UIDataDetectorTypeAll;
There's one caveat with data detectors: The default behavior of text views is to show the keyboard when tapped, so you can't tap the link of a data detector. For data detectors to work, you must set the editable property of the text view to NO. In Figure 4.33, the URL is underlined just as it would be in a web browser. Tapping it will launch the Safari application.
Figure 4.33 A text view with an active data detector.
Hiding the keyboard
A text view's keyboard behaves the same as a text field, with one important difference: Since a text view supports multiline editing, pressing the Return button on the keyboard will insert a carriage return instead of calling a delegate method. Just as with the text field, resign the text view's first responder status to hide the keyboard when you have finished editing the text. This is often done as an action within another control.
Scrolling the interface
You may have noticed that since the iPhone's keyboards are very large, they take up a lot of the screen and can overlap other controls when shown. It would be handy if your interface moved up when the keyboard appeared and then moved back down once it disappeared.
You can make that happen by placing the controls inside a UIScrollView. When the keyboard appears, you simply scroll everything up, scrolling back down when the keyboard hides.
To scroll the interface in response to the keyboard:
- Create and add a scroll view, making it the full size of the main view:
CGRect viewRect = [self.view bounds]; myScrollView = [[UIScrollView alloc] initWithFrame:viewRect]; myScrollView.contentSize = viewRect.size; [self.view addSubview:myScrollView];
- Add the controls to the scroll view instead of the main view (since you want them to scroll).
Implement the textViewDidBeginEditing: delegate method, which is called when the keyboard is shown.
Here you need to calculate both the bottom of the text view and the top of the keyboard and then tell the scroll view to scroll the difference. You must also look at the orientation property of the iPhone because the keyboard will have a different height in portrait mode than in landscape mode.
- Implement the textViewDidEndEditing: delegate so that when the keyboard is hidden, you scroll the text view to its original position. Code Listing 4.26 shows the completed code.
Code Listing 4.26 Scrolling an interface in response to a keyboard.