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