How to show\hide keyboard on entry focus in Xamarin for iOS?

A lot of us probably faced with the problem of Entry focus, the keyboard automatically on iOS no jumps, unlike Android. This behavior is more than unacceptable.

The first thing that comes to mind – is to write a renderer for Entry and start to handle UIKeyboard.WillHideNotification UIKeyboard.WillShowNotification.

The code for such solution might look like this:

protected virtual void OnKeyboardNotification 
   (NSNotification notification)
{
    try {
        var frameBegin = 
               UIKeyboard.FrameBeginFromNotification (notification);
        var frameEnd = 
               UIKeyboard.FrameEndFromNotification (notification);
 
        var parent = this.GetParent ();
        if (parent == null)
            return;
 
         if (frameBegin.Top == frameEnd.Top)
             return;
 
         if (frameBegin.Top> frameEnd.Top)
             parent.TranslateTo (0, - (frameBegin.Height / 2));
         else
             parent.TranslateTo (0, 0);
        } Catch (Exception ex) {
            Xamarin.Insights.Report (ex);
        }
    }

For a long time it was my only solution for this problem of focus and the keyboard on iOS in Xamarin.

However, there is an easier way to solve this problem. Xamarin really does this automatically on iOS, but the page content should be ScrollView.

In this case, when you set up focus to the Entry, all content of the page will be automatically moved up and we get the same behavior as on Android.

 

    <ScrollView>
         <Grid>
             <Grid.RowDefinitions>
                 <RowDefinition Height="4*"/>
                 <RowDefinition Height="35"/>
                 <RowDefinition Height="*"/>
             </Grid.RowDefinitions>
             <Grid.ColumnDefinitions>
                 <ColumnDefinition Width="*" />
                 <ColumnDefinition Width="Auto" />
                 <ColumnDefinition Width="5*" />
                 <ColumnDefinition Width="*" />
             </Grid.ColumnDefinitions>
             <Label Text="email" Grid.Row="1" Grid.Column="1" 
                 VerticalOptions="Center"/>
             <Entry Keyboard="Email" Placeholder="enter your email" 
                 Grid.Row="1" Grid.Column="2"/>
         </Grid>
     </ScrollView>

4 Responses

  1. Hello my friend! I want to say that this article is amazing, nice written and include approximately all important infos. I'd like to look more posts like this .
  2. That is a really good tip particularly to those new to the blogosphere. Short but very precise info… Appreciate your sharing this one. A must read post!
  3. Great post.
  4. It's impressive that you are getting thoughts from this post as well as from our discussion made here.

Leave a comment