How to detect keyboard events on hardware keyboard on iPhone (iOS)

亡梦爱人 提交于 2019-12-04 12:21:18

One way to accomplish this is to have a hidden extra (4th in your case) text field. Make it 1x1 px in size and transparent. Then make it the first responder when any of your other 3 text fields are not, and look for text change events in that hidden field to trigger your key input event.

You might also want to check the notification for a software keyboard appearing if you don't want it to stay visible as well.

For iOS 7.0 or later, you can return UIKeyCommands for the keyCommands property from any UIResponder, such as UIViewController:

Objective-C

// In a view or view controller subclass:
- (BOOL)canBecomeFirstResponder
{
    return YES;
}

- (NSArray *)keyCommands
{
    return @[ [UIKeyCommand keyCommandWithInput:@"\r" modifierFlags:0 action:@selector(enterPressed)] ];
}

- (void)enterPressed
{
    NSLog(@"Enter pressed");
}

Swift

// In a UIView/UIViewController subclass:
override func canBecomeFirstResponder() -> Bool {
    return true
}

override var keyCommands: [UIKeyCommand]? {
    return [ UIKeyCommand(input: "\r", modifierFlags: [], action: #selector(enterPressed)) ]
}

@objc func enterPressed() {
    print("Enter pressed")
}

As a followup to the response by @Patrick, here is how you do it in Xamarin.iOS:

public override bool CanBecomeFirstResponder
{
    get { return true; }
}

public override UIKeyCommand[] KeyCommands
{
    get
    {
         return new[]{ UIKeyCommand.Create((NSString)"\r", (UIKeyModifierFlags)0, new ObjCRuntime.Selector("enterPressed")) };
    }
}

[Export("enterPressed")]
private void OnEnterPressed()
{
    // Handle Enter Key
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!