Using the keyboard

In this recipe, we will discuss some important aspects of the device's virtual keyboard usage.

Getting ready

In the previous recipe, we discussed how to edit text. In this recipe, we will discuss some of the things we can or even must do to use the keyboard effectively. Create a new iPhone Single View Application project in Xamarin Studio and name it KeyboardApp.

How to do it...

Perform the following steps:

  1. Open the KeyboardAppViewController.xib file in Interface Builder.
  2. Add a UITextField object in the bottom-half portion of the view and connect it to an outlet.
  3. Save the document.
  4. Back in Xamarin Studio, enter the following code in the KeyboardAppViewController class:
    private NSObject kbdWillShow, kbdDidHide;
    public override void ViewDidLoad()
    {
    
      base.ViewDidLoad();
    
      this.emailField.KeyboardType = UIKeyboardType.EmailAddress;
      this.emailField.ReturnKeyType = UIReturnKeyType.Done;
    
      this.kbdWillShow = UIKeyboard.Notifications.ObserveWillShow((s, e) => {RectangleF kbdBounds = e.FrameEnd;
        RectangleF textFrame = this.emailField.Frame;
          textFrame.Y -= kbdBounds.Height;
      this.emailField.Frame = textFrame;
      } );
      this.kbdDidHide = UIKeyboard.Notifications.ObserveDidHide((s, e) => {
        RectangleF kbdBounds = e.FrameEnd;
        RectangleF textFrame = this.emailField.Frame;
        textFrame.Y += kbdBounds.Height;
        this.emailField.Frame = textFrame;
      } );
    
      this.emailField.ShouldReturn = delegate(UITextField textField) {
        return textField.ResignFirstResponder ();
      } ;
    
    }
  5. Compile and run the app on the simulator. Tap on the text field and watch it moving upwards to avoid being hidden from the keyboard. Tap the Done button on the keyboard and watch the text field returning to its original position when the keyboard hides.

How it works...

There are various types of keyboards in iOS. Since not all keys can be displayed at once due to the restricted screen size, it is a good practice to set the appropriate type of keyboard according to the text input we need the user to provide. In this project, we have set the keyboard to the Email Address type. We have also customized the type of Return key by setting it to Done in the following code:

this.emailField.KeyboardType = UIKeyboardType.EmailAddress;
this.emailField.ReturnKeyType = UIReturnKeyType.Done;

When the keyboard is displayed, it is the developer's responsibility to make sure it does not obstruct the essential UI elements. In this case, since we provide the user with the ability to enter some text input, we have to make sure that the text field is shown, so the user will be able to see what is being typed. For this, we add two observers in the default notification center using the following code:

// Add observers for the keyboard
this.kbdWillShow = UIKeyboard.Notifications.ObserveWillShow((s, e) => {

The notification center is iOS' mechanism for providing system-wide notifications. Normally, it can be accessed through the NSNotificationCenter.DefaultCenter static property. However, Xamarin.iOS provides some APIs that simplify things for us. In the example project for this recipe, you will find the usage of both APIs. In this recipe, we are using Xamarin's APIs.

By calling UIKeyboard.Notifications.ObserveWillShow and passing a handler to it, we subscribe to the notification center so that we get notified whenever the keyboard is about to be displayed. This handler is of the EventHandler<UIKeyboardEventArgs> type, and the UIKeyboardEventArgs parameter provides us with, among others, the frame of the keyboard after it has been shown (as shown in the following code):

// Get the keyboard's bounds
RectangleF kbdBounds = e.FrameEnd;

Then, we store the text field's frame in a variable using the following code:

// Get the text field's frame
RectangleF textFrame = this.emailField.Frame;

We reduce the frame's Y position using the following code value so that the text field will move upwards:

// Change the y position of the text field frame
textFrame.Y -= kbdBounds.Height;

When the new frame is set to emailField (as shown in the following code), it will move to the new position:

this.emailField.Frame = textFrame;

The second handler is needed for moving the text field back to its original position after the keyboard is closed. It is almost the same as the first handler, except for two differences. The UIKeyboard.Notifications.ObserveDidHide method is used. This method will trigger our handler after the keyboard is hidden. In this handler, we just make sure that we readjust the text field's position back to where it was.

The last few lines of code in the ViewDidLoad method set the ShouldReturn property of the UITextField class. This property accepts a delegate of the UITextFieldCondition type, as shown in the following code:

this.emailField.ShouldReturn = delegate(UITextField textField) {
  return textField.ResignFirstResponder ();
} ;

The handler we have added is called whenever the user taps the return key on the virtual keyboard. Here, we call the ResignFirstResponder method of UITextField, which will hide our keyboard.

There's more...

The two fields of the NSObject type in the class, which are assigned to the return values of the UIKeyboard.Notifications methods we used, hold information about the observers we added. For removing the two observers we have added here, add the following code:

NSNotificationCenter.DefaultCenter.RemoveObserver (this.kbdWillShow);
NSNotificationCenter.DefaultCenter.RemoveObserver (this.kbdDidHide);

Note

Care must be taken when developing an app that uses the keyboard and supports multiple interface orientations. If, for example, the keyboard appears in portrait orientation and the user changes to landscape orientation, both the keyboard's bounds and the text field's frame will be different and must be adjusted accordingly.

See also

  • The Displaying and editing text recipe
  • The Adjusting the UI orientation recipe in Chapter 9, Interacting with Device Hardware