iOS toggle default keyboard from ABC mode to 123 mode via code?

落爺英雄遲暮 提交于 2019-12-10 10:38:59

问题


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.



来源:https://stackoverflow.com/questions/25150077/ios-toggle-default-keyboard-from-abc-mode-to-123-mode-via-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!