4

I have an app with a login page that has three fields for three different random characters. When the user leaves the last field, the soft keyboard disappears and the user can touch a "login" button on screen.

When there is a hardware keyboard (bluetooth or physical) attached, I'd like to be able to hit "enter" on it. However because the user is not in a field, I can't see how to detect this key being pressed.

Would anyone have advice on which class handles key press events? Presumably there is a delegate that I can use to receive these but my searches through the SDK haven't found anything.

Thanks

hocker
  • 688
  • 6
  • 18

3 Answers3

15

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 var canBecomeFirstResponder: Bool {
    true
}

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

@objc func enterPressed() {
    print("Enter pressed")
}
mmackh
  • 3,550
  • 3
  • 35
  • 51
Patrick Pijnappel
  • 7,317
  • 3
  • 39
  • 39
1

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
}
Kraig McConaghy
  • 258
  • 4
  • 4
1

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.

hotpaw2
  • 70,107
  • 14
  • 90
  • 153