iOS toggle default keyboard from ABC mode to 123 m

2019-05-29 03:34发布

问题:

I can see how to set the keyboard's overall type via:

self.myTextView.keyboardType = UIKeyboardTypeDefault;

How can I toggle the default keyboard's mode from ABC to 123 and back again via code? Basically the moment the user taps the @ character (the @ symbol is available when they're in 123 mode) I want to switch their keyboard back to ABC mode.

Any ideas?

回答1:

You might be able to accomplish this in by using the UITextViewDelegate. It allows you to intercept the keys as they are pressed in the UITextView. This will allow you to switch keyboards when the user presses a certain key. In order to revert back to the default state of the UIKeyboardTypeDefault keyboard, you'll need to change the keyboard type to another, then back to the default.

In your ViewController.h file, make it implement the UITextViewDelegate protocol:

@interface ViewController : UIViewController <UITextViewDelegate>

In your ViewController's viewDidLoad method in the ViewController.m, set the textField's delegate to the view controller:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.myTextView.delegate = self;
}

Finally, we need to capture the key as it is being entered and change the keyboard appropriately. We do this in the shouldChangeCharactersInRange: method.

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if( [@"@" isEqualToString:text] )
    {
        NSLog( @"Toggling keyboard type");
        textView.inputView = nil;
        [textView resignFirstResponder];
        [textView setKeyboardType:UIKeyboardTypeEmailAddress];
        [textView becomeFirstResponder];
        [textView reloadInputViews];

        textView.inputView = nil;
        [textView resignFirstResponder];
        [textView setKeyboardType:UIKeyboardTypeDefault];
        [textView becomeFirstResponder];
        [textView reloadInputViews];

    }
    return YES;
}

So I was originally confused and thought you actually wanted to change the keyboard type. Now that I'm reading your comment, I realize that you're actually wanting to reset the keyboard to it's default state of showing the letters, instead of numbers and special characters. The above code now does that.