How to detect when user changes keyboards?

2019-01-31 14:56发布

Is there some way to detect when the user changes keyboard types, specifically to the Emoji keyboard in this case?

2条回答
Fickle 薄情
2楼-- · 2019-01-31 15:13

You can use UITextInputMode to detect the current language of the currentInputMode -- emoji is considered a language. From the docs:

An instance of the UITextInputMode class represents the current text-input mode. You can use this object to determine the primary language currently being used for text input.

You can test for the emoji keyboard like this:

NSString *language = [[UITextInputMode currentInputMode] primaryLanguage];
BOOL isEmoji = [language isEqualToString:@"emoji"];
if (isEmoji)
{
   // do something
}

You can be notified of the input mode changing via the UITextInputCurrentInputModeDidChangeNotification. This will post when the current input mode changes.

Here's a simple app which prints an NSLog whenever the mode changes:

- (void)viewDidLoad
{
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self
         selector:@selector(changeInputMode:) 
             name:UITextInputCurrentInputModeDidChangeNotification object:nil];}
}

-(void)changeInputMode:(NSNotification *)notification
{
    NSString *inputMethod = [[UITextInputMode currentInputMode] primaryLanguage];
    NSLog(@"inputMethod=%@",inputMethod);
}  

Or if you prefer Swift:

import UIKit

class ViewController: UIViewController 
{

    override func viewDidLoad() {
        super.viewDidLoad()

        NSNotificationCenter.defaultCenter().addObserver(self, 
       selector: "changeInputMode:", 
           name: UITextInputCurrentInputModeDidChangeNotification, object: nil)
    }

    func changeInputMode(notification : NSNotification)
    {
        let inputMethod = UITextInputMode.currentInputMode().primaryLanguage
        println("inputMethod: \(inputMethod)")
    }


}
查看更多
仙女界的扛把子
3楼-- · 2019-01-31 15:21

Swift 4:

NotificationCenter.default.addObserver(self,
     selector: #selector(FirstViewController.changeInputMode(_:)),
     name: NSNotification.Name.UITextInputCurrentInputModeDidChange, object: nil)

func changeInputMode(_ notification: Notification) 
    {
        let inputMethod = UITextInputMode.activeInputModes.description
        print("keyboard changed to \(inputMethod.description)")
    }
查看更多
登录 后发表回答