rotorgames / Rg.Plugins.Popup

Xamarin Forms popup plugin
MIT License
1.15k stars 337 forks source link

Can RgPopup capture hardware keyboard commands? #694

Open breetzn opened 2 years ago

breetzn commented 2 years ago

💬 Questions and Help

In our xamarin app, we allow the user to navigate the app using a hardware keyboard (up, down, left, right for ex.). Is there a way to capture the keyboard commands in our RgPopup view?

This is not an issue for Android as the keyboard capturing is done at an app level. But for iOS, we've had to create custom renderers for our views to capture the keyboard input. Here is an example of how we would capture the user hitting the "up" arrow on a keyboard:

[assembly: ExportRenderer(typeof(SettingsPage), typeof(SettingsPageRenderer))]
namespace Project.iOS.Renderers
{
    public class SettingsPageRenderer : PageRenderer
    {
        private string _RecvValue = string.Empty;

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

        protected override void OnElementChanged(VisualElementChangedEventArgs e)
        {
            base.OnElementChanged(e);
            string key = string.Empty;
            var selector = new ObjCRuntime.Selector("KeyPressed:");

            UIKeyCommand acceleratorUp = UIKeyCommand.Create(UIKeyCommand.UpArrow, 0, selector);
            AddKeyCommand(acceleratorUp);

            this.AddKeyCommand(acceleratorUp);
        }

        [Export("KeyPressed:")]
        public void KeyRecv(UIKeyCommand cmd)
        {
            if (cmd == null)
                return;
            string inputValue = (string)cmd.Input;
            switch (inputValue)
            {
                case "UIKeyInputUpArrow":
                    inputValue = KeyboardConstants.Up;
                    break;
            }
            ((SettingsPage)Element)?.HandleHardwareKeyboard(inputValue);
        }
    }
}

Once we push the RgPopup page, the "SettingsPage" is no longer in view, so we cannot capture the keyboard commands. A way to do this for the RgPopup would be awesome!

Any help is appreciated! Thanks!

LuckyDucko commented 2 years ago

So, since popup pages are based on the same PageRenderer base type, we may be able to adjust it in the future so you can have your keypresses code merged in. Currently, my next task is working on our MAUI upgrade, however what I can recommend to you is to download the codebase, and make a reference (here is a link to help)

Try and add your adjustments to the iOS renderer directly, and see If they work out? With that in mind, we might be able to take a PR to add it into the codebase