Managing the Keyboard
Although many UIKit objects display the keyboard automatically in response to user interactions, your application still has some responsibilities for configuring and managing the keyboard. The following sections describe those responsibilities.
=> Receiving Keyboard Notifications
When the keyboard is shown or hidden, iPhone OS sends out the following notifications to any registered observers:
■ UIKeyboardWillShowNotification
■ UIKeyboardDidShowNotification
■ UIKeyboardWillHideNotification
■ UIKeyboardDidHideNotification
The system sends keyboard notifications when the keyboard first appears, when it disappears, any time the owner of the keyboard changes, or any time your application’s orientation changes. In each situation, the system sends only the appropriate subset of messages. For example, if the owner of the keyboard changes, the system sends a UIKeyboardWillHideNotification message, but not a UIKeyboardDidHideNotification message, to the current owner because the change never causes the keyboard to be hidden. The delivery of the UIKeyboardWillHideNotification is simply a way to alert the current owner that it is about to lose the keyboard focus. Changing the orientation of the keyboard does send both will and did hide notifications, however, because the keyboards for each orientation are different and thus the original must be hidden before the new one is displayed.
Each keyboard notification includes information about the size and position of the keyboard on the screen.
You should always use the information in these notifications as opposed to assuming the keyboard is a particular size or in a particular location. The size of the keyboard is not guaranteed to be the same from one input method to another and may also change between different releases of iPhone OS. In addition, even for a single language and system release, the keyboard dimensions can vary depending on the orientation of your application. For example, Figure shows the relative sizes of the URL keyboard in both the portrait and landscape modes. Using the information inside the keyboard notifications ensures that you always have the correct size and position information.
Figure: Relative keyboard sizes in portrait and landscape modes
■ UIKeyboardWillShowNotification
■ UIKeyboardDidShowNotification
■ UIKeyboardWillHideNotification
■ UIKeyboardDidHideNotification
The system sends keyboard notifications when the keyboard first appears, when it disappears, any time the owner of the keyboard changes, or any time your application’s orientation changes. In each situation, the system sends only the appropriate subset of messages. For example, if the owner of the keyboard changes, the system sends a UIKeyboardWillHideNotification message, but not a UIKeyboardDidHideNotification message, to the current owner because the change never causes the keyboard to be hidden. The delivery of the UIKeyboardWillHideNotification is simply a way to alert the current owner that it is about to lose the keyboard focus. Changing the orientation of the keyboard does send both will and did hide notifications, however, because the keyboards for each orientation are different and thus the original must be hidden before the new one is displayed.
Each keyboard notification includes information about the size and position of the keyboard on the screen.
You should always use the information in these notifications as opposed to assuming the keyboard is a particular size or in a particular location. The size of the keyboard is not guaranteed to be the same from one input method to another and may also change between different releases of iPhone OS. In addition, even for a single language and system release, the keyboard dimensions can vary depending on the orientation of your application. For example, Figure shows the relative sizes of the URL keyboard in both the portrait and landscape modes. Using the information inside the keyboard notifications ensures that you always have the correct size and position information.
Figure: Relative keyboard sizes in portrait and landscape modes
Note: The rectangle contained in the UIKeyboardBoundsUserInfoKey of the info dictionary should be used only for the size information it contains. Do not use the origin of the rectangle (which is always {0.0, 0.0}) in rectangle-intersection operations. Because the keyboard is animated into position, the actual bounding rectangle of the keyboard changes over time. The starting and ending positions of the keyboard are therefore stored in the info dictionary under the UIKeyboardCenterBeginUserInfoKey and UIKeyboardCenterEndUserInfoKey keys, and from these values you can compute the origin.
One reason to use keyboard notifications is so that you can reposition content that is obscured by the keyboard when it is visible. For information on how to handle this scenario.
=> Displaying the Keyboard
When the user taps a view, the system automatically designates that view as the first responder. When this happens to a view that contains editable text, the view initiates an editing session for that text. At the beginning of that editing session, the view asks the system to display the keyboard, if it is not already visible.
If the keyboard is already visible, the change in first responder causes text input from the keyboard to be redirected to the newly tapped view.
Because the keyboard is displayed automatically when a view becomes the first responder, you often do not need to do anything to display it. However, you can programmatically display the keyboard for an editable text view by calling that view’s becomeFirstResponder method. Calling this method makes the target view the first responder and begins the editing process just as if the user had tapped on the view.
If your application manages several text-based views on a single screen, it is a good idea to track which view is currently the first responder so that you can dismiss the keyboard later.
If the keyboard is already visible, the change in first responder causes text input from the keyboard to be redirected to the newly tapped view.
Because the keyboard is displayed automatically when a view becomes the first responder, you often do not need to do anything to display it. However, you can programmatically display the keyboard for an editable text view by calling that view’s becomeFirstResponder method. Calling this method makes the target view the first responder and begins the editing process just as if the user had tapped on the view.
If your application manages several text-based views on a single screen, it is a good idea to track which view is currently the first responder so that you can dismiss the keyboard later.
=> Dismissing the Keyboard
Although it typically displays the keyboard automatically, the system does not dismiss the keyboard automatically. Instead, it is your application’s responsibility to dismiss the keyboard at the appropriate time.
Typically, you would do this in response to a user action. For example, you might dismiss the keyboard when the user taps the Return or Done button on the keyboard or taps some other button in your application’s interface. Depending on how you configured the keyboard, you might need to add some additional controls to your user interface to facilitate the keyboard’s dismissal.
To dismiss the keyboard, you call the resignFirstResponder method of the text-based view that is currently the first responder. When a text view resigns its first responder status, it ends its current editing session, notifies its delegate of that fact, and dismisses the keyboard. In other words, if you have a variable called myTextField that points to the UITextField object that is currently the first responder, dismissing the keyboard is as simple as doing the following:
[myTextField resignFirstResponder];
Everything from that point on is handled for you automatically by the text object.
Typically, you would do this in response to a user action. For example, you might dismiss the keyboard when the user taps the Return or Done button on the keyboard or taps some other button in your application’s interface. Depending on how you configured the keyboard, you might need to add some additional controls to your user interface to facilitate the keyboard’s dismissal.
To dismiss the keyboard, you call the resignFirstResponder method of the text-based view that is currently the first responder. When a text view resigns its first responder status, it ends its current editing session, notifies its delegate of that fact, and dismisses the keyboard. In other words, if you have a variable called myTextField that points to the UITextField object that is currently the first responder, dismissing the keyboard is as simple as doing the following:
[myTextField resignFirstResponder];
Everything from that point on is handled for you automatically by the text object.
=> Moving Content That Is Located Under the Keyboard
When asked to display the keyboard, the system slides it in from the bottom of the screen and positions it over your application’s content. Because it is placed on top of your content, it is possible for the keyboard to be placed on top of the text object that the user wanted to edit. When this happens, you must adjust your content so that the target object remains visible.
Adjusting your content typically involves temporarily resizing one or more views and positioning them so that the text object remains visible. The simplest way to manage text objects with the keyboard is to embed them inside a UIScrollView object (or one of its subclasses like UITableView). When the keyboard is displayed, all you have to do is resize the scroll view and scroll the desired text object into position. Thus, in response to a UIKeyboardDidShowNotification, your handler method would do the following:
1. Get the size of the keyboard.
2. Subtract the keyboard height from the height of your scroll view.
3. Scroll the target text field into view.
Note: As of iPhone OS 3.0, the UITableViewController class automatically resizes and repositions its table view when there is in-line editing of text fields. See “View Controllers and Navigation-Based Applications” in Table View Programming Guide for iPhone OS.
Figure illustrates the preceding steps for a simple application that embeds several text fields inside a UIScrollView object. When the keyboard appears, the notification handler method resizes the scroll view and then uses the scrollRectToVisible:animated: method of UIScrollView to scroll the tapped text field (in this case the email field) into view.
Figure 5-6 Adjusting content to accommodate the keyboard
Adjusting your content typically involves temporarily resizing one or more views and positioning them so that the text object remains visible. The simplest way to manage text objects with the keyboard is to embed them inside a UIScrollView object (or one of its subclasses like UITableView). When the keyboard is displayed, all you have to do is resize the scroll view and scroll the desired text object into position. Thus, in response to a UIKeyboardDidShowNotification, your handler method would do the following:
1. Get the size of the keyboard.
2. Subtract the keyboard height from the height of your scroll view.
3. Scroll the target text field into view.
Note: As of iPhone OS 3.0, the UITableViewController class automatically resizes and repositions its table view when there is in-line editing of text fields. See “View Controllers and Navigation-Based Applications” in Table View Programming Guide for iPhone OS.
Figure illustrates the preceding steps for a simple application that embeds several text fields inside a UIScrollView object. When the keyboard appears, the notification handler method resizes the scroll view and then uses the scrollRectToVisible:animated: method of UIScrollView to scroll the tapped text field (in this case the email field) into view.
Figure 5-6 Adjusting content to accommodate the keyboard
1. User taps email field 2. Scroll view resized to new height 3. Email field scrolled into view
Note: When setting up your own scroll views, be sure to configure the autoresizing rules for any content views appropriately. In the preceding figure, the text fields are actually subviews of a generic UIView object,
which is itself a subview of the UIScrollView object. If the generic view’s UIViewAutoresizingFlexibleWidth and UIViewAutoresizingFlexibleHeight autoresizing options are set, changing the scroll view’s frame size also changes the frame of the generic view, which could yield undesirable results. Disabling these options for that view ensures that the view retains its size and its contents are scrolled correctly.
Shows the code for registering to receive keyboard notifications and shows the handler methods for those notifications. This code is implemented by the view controller that manages the scroll view, and the scrollView variable is an outlet that points to the scroll view object. Each handler method gets the keyboard size from the info dictionary of the notification and adjusts the scroll view height by the corresponding amount. In addition, the keyboardWasShown: method scrolls the rectangle of the active text field, which is stored in a custom variable (called activeField in this example) that is a member variable of the view controller and set in the textFieldDidBeginEditing: delegate method.
Handling the keyboard notifications
// Call this method somewhere in your view controller setup code.
- (void)registerForKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasHidden:)
name:UIKeyboardDidHideNotification object:nil];
}
// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
if (keyboardShown)
return;
NSDictionary* info = [aNotification userInfo];
// Get the size of the keyboard.
NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
CGSize keyboardSize = [aValue CGRectValue].size;
// Resize the scroll view (which is the root view of the window)
CGRect viewFrame = [scrollView frame];
viewFrame.size.height -= keyboardSize.height;
scrollView.frame = viewFrame;
// Scroll the active text field into view.
CGRect textFieldRect = [activeField frame];
[scrollView scrollRectToVisible:textFieldRect animated:YES];
keyboardShown = YES;
}
// Called when the UIKeyboardDidHideNotification is sent
- (void)keyboardWasHidden:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
// Get the size of the keyboard.
NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
CGSize keyboardSize = [aValue CGRectValue].size;
// Reset the height of the scroll view to its original value
CGRect viewFrame = [scrollView frame];
viewFrame.size.height += keyboardSize.height;
scrollView.frame = viewFrame;
keyboardShown = NO;
}
The keyboardShown variable from the preceding listing is a Boolean value used to track whether the keyboard is already visible. If your interface has multiple text fields, the user can tap between them to edit the values in each one. When that happens, however, the keyboard does not disappear but the system does still generate UIKeyboardDidShowNotification notifications each time editing begins in a new text field. By tracking whether the keyboard was actually hidden, this code prevents the scroll view from being reduced in size more than once.
Shows some additional code used by the view controller to set and clear the activeField variable in the preceding example. During initialization, each text field in the interface sets the view controller as its delegate. Therefore, when a text field becomes active, it calls these methods. For more information on text fields and their delegate notifications, see UITextField Class Reference.
Additional methods for tracking the active text field.
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
activeField = textField;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
activeField = nil;
}
Shows some additional code used by the view controller to set and clear the activeField variable in the preceding example. During initialization, each text field in the interface sets the view controller as its delegate. Therefore, when a text field becomes active, it calls these methods. For more information on text fields and their delegate notifications, see UITextField Class Reference.
Additional methods for tracking the active text field.
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
activeField = textField;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
activeField = nil;
}
No comments:
Post a Comment