Reputation: 1441
In my Xamarin.iOS app (C#), I have a iPhoneOSGameView
(which inherits from UIView
), and I would like to capture key presses from an external (say bluetooth) keyboard.
Since this is to add support for keyboard control in a game, I want to be able to respond to these events without having to place a textbox or any other text field as proposed in this question (actually, they're not capturing key presses, but textbox changes, which is completely different from what I want to do)
In Android, I can achieve this by overriding OnKeyDown
and OnKeyUp
in my activity, but there seem to be no similar events either on UIView
or UIViewController
.
Is there a way to capture key presses and key releases in either UIView
or UIViewController
?
Since this is for Xamarin.iOS, I would certainly prefer a C# answer, but I guess I can read Objective-C if needed.
Upvotes: 3
Views: 1556
Reputation: 1441
In order to get keyboard events on a UIView
, you need to adopt the UIKeyInput
protocol.
To do this, first you have to decorate your view class with [Adopts("UIKeyInput")]
.
Then, you need to implement all the methods required by UIKeyInput
:
[Export("hasText")]
bool HasText { get { return false; } }
[Export("insertText:")] // Don't forget the colon
void InsertText(string text) // This is what gets called on a key press
{
}
[Export("deleteBackward")]
void DeleteBackward()
{
}
Finally, you have to let iOS know that this can become a first responder (whatever that is):
public override bool CanBecomeFirstResponder { get { return true; } }
And then you have to become the first responder when the view is coming up, for example on WillEnterForeground
:
view.BecomeFirstResponder();
Don't forget to stop being the first responder when the view is leaving focus, for example on DidEnterBackground
:
view.ResignFirstResponder();
Finally, it would be a good idea to implement inputView
and have it return an empty UIView
so the default keyboard won't come out:
private UIView inputView;
// ...
inputView = new UIView(new RectangleF());
// And somewhere else...
[Export("inputView")]
public new UIView InputView { get { return inputView; } }
Thanks to @radical in the chat for helping me figure this out.
This solution is not about getting key down and key up events, but about creating a new textbox. It would be awesome if somebody else pointed out how to actually get the lower-level key down and key up events, if that's even possible.
Upvotes: 4