user1229084
user1229084

Reputation: 103

Close the keyboard once button pressed in Xamarin

In a view controller I have a 2 text boxes (UITextField) and a submit button. The text boxes pop up the ASCII keyboard. The Submit button takes the values from the text boxes and does something with them.

  1. When the keyboard is open, how do I kill it once the submit button is pressed
  2. The keyboard has a Next button, how do I get it to go to the next field.

Using Xamarin Studio 4.0.12

Thank you!

Upvotes: 4

Views: 4599

Answers (2)

Yksh
Yksh

Reputation: 3306

Just have a try with this ,

It's just a sample,

NSObject keyboardShowObserver;
NSObject keyboardHideObserver;
public override void ViewWillAppear(bool animated) {
    base.ViewWillAppear(animated);

    keyboardShowObserver = NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.WillShowNotification, (notification) => {
        NSValue nsKeyboardBounds = (NSValue)notification.UserInfo.ObjectForKey(UIKeyboard.BoundsUserInfoKey);
        RectangleF keyboardBounds = nsKeyboardBounds.RectangleFValue;
        float height = View.Bounds.Height - keyboardBounds.Height;
        if (NavigationController != null && NavigationController.TabBarController != null && NavigationController.TabBarController.TabBar != null) {
            // Re-add tab bar height since it is hidden under keyboard but still excluded from View.Bounds.Height.
            height += NavigationController.TabBarController.TabBar.Frame.Height;
        }

        someScrollView.Frame = new RectangleF(someScrollView.Frame.Location, new SizeF(View.Bounds.Width, height));
    });
    keyboardHideObserver = NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.WillHideNotification, (notification) => {
        UIApplication.EnsureUIThread();

        someScrollView.Frame = new RectangleF(someScrollView.Frame.Location, View.Bounds.Size);
    });
}
public override void ViewDidDisappear(bool animated) {
    base.ViewDidDisappear(animated);
    if (keyboardShowObserver != null) {
        NSNotificationCenter.DefaultCenter.RemoveObserver(keyboardShowObserver);
    }
    if (keyboardHideObserver != null) {
        NSNotificationCenter.DefaultCenter.RemoveObserver(keyboardHideObserver);
    }
}

Upvotes: 0

Mohib Sheth
Mohib Sheth

Reputation: 1135

You need to do what incmiko suggested. Here's the code in C#

Part 1.

txtUsername.ShouldReturn = TextFieldShouldReturn;
txtPassword.ShouldReturn = TextFieldShouldReturn;

create a function in your view

private bool TextFieldShouldReturn(UITextField tf)
{
    //change the code below as per your validation
    if (tf == _txtUsername)
    {
        _txtPassword.BecomeFirstResponder();
        return true;
    }
    if(tf == _txtPassword)
    {
        // validate field inputs as per your requirement
        tf.ResignFirstResponder();
        return true;
    }
    return true;
}

Upvotes: 7

Related Questions