How to detect when user changes keyboards?

拟墨画扇 提交于 2019-12-18 10:32:27

问题


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


回答1:


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)")
    }


}



回答2:


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)")
    }


来源:https://stackoverflow.com/questions/24167856/how-to-detect-when-user-changes-keyboards

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