Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I unfocus an Entry in a NET MAUI application, particularly on iOS, when the user clicks outside the entry or anywhere else on the screen?

Tags:

ios

maui

While in entry focus, I cannot unfocus by clicking anywhere on the screenthe only way to unfocus entry is click return button on keyboard. How can I unfocus an Entry in a NET MAUI application, particularly on iOS, when the user clicks outside the entry or anywhere else on the screen?

like image 428
Alpay Çalışır Avatar asked Sep 03 '25 17:09

Alpay Çalışır


2 Answers

Set HideSoftInputOnTapped="True" on your ContentPage.

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             HideSoftInputOnTapped="True"
             x:Class="MyApp.MainPage">
    <Entry />
</ContentPage>
like image 161
Riccardo Minato Avatar answered Sep 05 '25 06:09

Riccardo Minato


I used this code on Android to do the trick. I did not yet find any solution for iOS.

public class MainActivity : MauiAppCompatActivity
{
    // Other Code

    public override bool DispatchTouchEvent(MotionEvent? e)
    {
        if (e!.Action == MotionEventActions.Down)
        {
            var focusedElement = CurrentFocus;
            if (focusedElement is EditText editText)
            {
                var editTextLocation = new int[2];
                editText.GetLocationOnScreen(editTextLocation);
                var clearTextButtonWidth = 100;
                var editTextRect = new Rect(editTextLocation[0], editTextLocation[1], editText.Width + clearTextButtonWidth, editText.Height);

                var touchPosX = (int)e.RawX;
                var touchPosY = (int)e.RawY;
                if (!editTextRect.Contains(touchPosX, touchPosY))
                {
                    editText.ClearFocus();
                    var inputService = GetSystemService(Context.InputMethodService) as InputMethodManager;
                    inputService?.HideSoftInputFromWindow(editText.WindowToken, 0);
                }
            }
        }
        return base.DispatchTouchEvent(e);
    }
}
like image 37
Zumpfiii Avatar answered Sep 05 '25 06:09

Zumpfiii



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!