Код: Выделить всё
private void SetupKeyboardListener()
{
#if MACCATALYST
var nativeWindow = UIApplication.SharedApplication.KeyWindow;
if (nativeWindow != null)
{
nativeWindow.RootViewController.View.AddSubview(new KeyResponder(OnLeftArrowKeyPressed, OnRightArrowKeyPressed, OnCKeyPressed, OnVKeyPressed, OnKeyReleased));
}
#endif
}
private void OnLeftArrowKeyPressed()
{
Console.WriteLine("Left arrow pressed");
Globals.PlayerSpeedX = -1;
}
private void OnRightArrowKeyPressed()
{
Console.WriteLine("Right arrow pressed");
Globals.PlayerSpeedX = 1;
}
private void OnKeyReleased()
{
Console.WriteLine("Key released");
Globals.PlayerSpeedX = 0;
}
}
public class KeyResponder : UIView
{
private readonly Action onLeftArrowKeyPressed;
private readonly Action onRightArrowKeyPressed;
private readonly Action onCKeyPressed;
private readonly Action onVKeyPressed;
private readonly Action onKeyReleased;
public KeyResponder(Action onLeftArrowKeyPressed, Action onRightArrowKeyPressed, Action onCKeyPressed, Action onVKeyPressed, Action onKeyReleased)
{
this.onLeftArrowKeyPressed = onLeftArrowKeyPressed;
this.onRightArrowKeyPressed = onRightArrowKeyPressed;
this.onCKeyPressed = onCKeyPressed;
this.onVKeyPressed = onVKeyPressed;
this.onKeyReleased = onKeyReleased;
Frame = UIScreen.MainScreen.Bounds; // Rozprostřeme přes celé okno
BackgroundColor = UIColor.Clear; // Průhledné pozadí
BecomeFirstResponder();
}
public override bool CanBecomeFirstResponder => true;
public override void PressesBegan(NSSet presses, UIPressesEvent evt)
{
foreach (UIPress press in presses)
{
if (press.Key != null)
{
switch (press.Key.KeyCode)
{
case UIKeyboardHidUsage.KeyboardLeftArrow:
onLeftArrowKeyPressed?.Invoke();
break;
case UIKeyboardHidUsage.KeyboardRightArrow:
onRightArrowKeyPressed?.Invoke();
break;
case UIKeyboardHidUsage.KeyboardC:
onCKeyPressed?.Invoke();
break;
case UIKeyboardHidUsage.KeyboardV:
onVKeyPressed?.Invoke();
break;
}
}
}
base.PressesBegan(presses, evt);
}
public override void PressesEnded(NSSet presses, UIPressesEvent evt)
{
foreach (UIPress press in presses)
{
if (press.Key != null)
{
switch (press.Key.KeyCode)
{
case UIKeyboardHidUsage.KeyboardLeftArrow:
case UIKeyboardHidUsage.KeyboardRightArrow:
onKeyReleased?.Invoke();
break;
}
}
}
base.PressesEnded(presses, evt);
}
}
Подробнее здесь: https://stackoverflow.com/questions/793 ... accatalyst