XamaWIN – Dismiss button for iOS keyboard using Effects

Xamawin • zam-ah win | noun
A quick, easy to implement enhancement for a Xamarin App that improves performance, appearance, or functionality


A common frustration I run into while developing for Xamarin.Forms is that there is not an out of the box/obvious way for iOS to dismiss the keyboard. With the default renderer, a user may need to click “anywhere on the screen” to dismiss the keyboard while filling out a form. In a recent project, this came up in particular for an entry with a Numeric keyboard.

Keep in mind, on Android (and even Windows Phone!) there is either a native soft keyboard dismiss or we can expect the user to be familiar with the hardware back button. So! Here’s how we get the same on iOS, using Effects

First, let’s tackle the effect in our iOS project:

using System;
using CoreGraphics;
using PrismForms.iOS.Effects;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ResolutionGroupName("EffectsSample")]
[assembly: ExportEffect(typeof(SampleEntryEffect), "SampleEntryEffect")]
namespace PrismForms.iOS.Effects
{
    public class SampleEntryEffect: PlatformEffect
    {
        protected override void OnAttached()
        {
            var entry = (UITextField)Control;

            // Do some other cool Effect stuff here to customize the appearance on iOS

            entry.InputAccessoryView = BuildDismiss();
        }

        protected override void OnDetached()
        {

        }

        private UIToolbar BuildDismiss()
        {
            var toolbar = new UIToolbar(new CGRect(0.0f, 0.0f, Control.Frame.Size.Width, 44.0f));

            toolbar.Items = new[]
            {
                new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace),
                new UIBarButtonItem(UIBarButtonSystemItem.Done, delegate { Control.ResignFirstResponder(); })
            };

            return toolbar;
        }
    }
}

From here, we simply apply it in our view, like so:

View.xaml

                <Entry x:Name="SampleEntry" Keyboard="Numeric" Text="{Binding SettingOne}" AbsoluteLayout.LayoutBounds="1,10,.75,40" AbsoluteLayout.LayoutFlags="XProportional,WidthProportional" />

View.xaml.cs

        public SettingsPage()
        {
            InitializeComponent();

           SampleEntry.Effects.Add(Effect.Resolve("EffectsSample.SampleEntryEffect"));
        }

The before and after makes the benefit of this quick change immediately apparent:

But what if we want to do everything in xaml? Well, thats a post for another time 🙃. For now, you can find this example in my Prism.Forms bootstrap repository for reference.

One thought on “XamaWIN – Dismiss button for iOS keyboard using Effects

Leave a comment