Is there some way to detect when the user changes keyboard types, specifically to the Emoji keyboard in this case?
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)")
}
}
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